@automagik/genie 4.260421.3 → 4.260421.5

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
@@ -486,13 +486,13 @@ ${bin} set-option -w pane-active-border-style "fg=$COLOR"
486
486
  `),retentionRan=!0}catch(retErr){retentionRan=!0;let msg=retErr instanceof Error?retErr.message:String(retErr);process.stderr.write(`[genie] retention cleanup warning: ${msg}
487
487
  `)}}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=join14(home,"serve.pid"),raw=null;try{raw=readFileSync7(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&&currentStartTime===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=join14(home,"serve.pid"),hasPidFile=existsSync12(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(existsSync12(resolved))return resolved}catch{}let globalBin=join14(homedir10(),".bun","bin","pgserve");if(existsSync12(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??join14(homedir10(),".genie"),DATA_DIR=join14(GENIE_HOME,"data","pgserve"),LOCKFILE_PATH=join14(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(`
488
488
  `).map((line)=>tokenizePath(redactFreeText(line))).join(`
489
- `)),"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_team_ls_drift_detected={};__export(exports_rot_team_ls_drift_detected,{schema:()=>schema27,TYPE:()=>TYPE26,SCHEMA_VERSION:()=>SCHEMA_VERSION26,KIND:()=>KIND26});var SCHEMA_VERSION26=1,TYPE26="rot.team-ls-drift.detected",KIND26="event",DivergenceKindSchema,DivergentCountSchema,ObservedStateJsonSchema,schema27;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"),schema27=exports_external.object({divergence_kind:DivergenceKindSchema,divergent_count:DivergentCountSchema,observed_state_json:ObservedStateJsonSchema}).strict()});var exports_runbook_triggered={};__export(exports_runbook_triggered,{schema:()=>schema28,TYPE:()=>TYPE27,SCHEMA_VERSION:()=>SCHEMA_VERSION27,KIND:()=>KIND27});var SCHEMA_VERSION27=1,TYPE27="runbook.triggered",KIND27="event",RuleSchema,EvidenceCountSchema,CorrelationIdSchema,WindowMinutesSchema,RecommendedSqlSchema,EvidenceSummarySchema,schema28;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"),schema28=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:()=>schema29,TYPE:()=>TYPE28,SCHEMA_VERSION:()=>SCHEMA_VERSION28,KIND:()=>KIND28});var SCHEMA_VERSION28=1,TYPE28="schema.violation",KIND28="event",OffendingTypeSchema2,RejectedBytesSchema,IssueSchema,schema29;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"),schema29=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:()=>schema30,TYPE:()=>TYPE29,SCHEMA_VERSION:()=>SCHEMA_VERSION29,KIND:()=>KIND29});var SCHEMA_VERSION29=1,TYPE29="session.id.written",KIND29="event",AgentIdSchema5,SessionIdSchema3,ExecutorSchema4,OriginSchema,DiffSchema2,schema30;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"),schema30=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:()=>schema31,TYPE:()=>TYPE30,SCHEMA_VERSION:()=>SCHEMA_VERSION30,KIND:()=>KIND30});var SCHEMA_VERSION30=1,TYPE30="session.reconciled",KIND30="event",AgentIdSchema6,SessionIdSchema4,ReasonSchema6,DiffSchema3,schema31;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"),schema31=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:()=>schema32,TYPE:()=>TYPE31,SCHEMA_VERSION:()=>SCHEMA_VERSION31,KIND:()=>KIND31});var SCHEMA_VERSION31=1,TYPE31="state_transition",KIND31="event",EntityKindSchema,EntityIdSchema2,FromSchema2,ToSchema2,ReasonSchema7,ActorSchema3,DiffSchema4,schema32;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"),schema32=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:()=>schema33,TYPE:()=>TYPE32,SCHEMA_VERSION:()=>SCHEMA_VERSION32,KIND:()=>KIND32});var SCHEMA_VERSION32=1,TYPE32="stream.gap.detected",KIND32="event",ConsumerIdSchema2,IdSchema,CountSchema6,schema33;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"),schema33=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:()=>schema34,TYPE:()=>TYPE33,SCHEMA_VERSION:()=>SCHEMA_VERSION33,KIND:()=>KIND33,DEFAULT_TIER:()=>DEFAULT_TIER5});var SCHEMA_VERSION33=1,TYPE33="team.create",KIND33="event",DEFAULT_TIER5="audit",TeamNameSchema,WishSlugSchema,RepoPathHashSchema,ActorSchema4,MemberCountSchema,AutoSchema,schema34;var init_team_create=__esm(()=>{init_zod();init_redactors();TeamNameSchema=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"),schema34=exports_external.object({team_name:TeamNameSchema,wish_slug:WishSlugSchema,repo_path_hash:RepoPathHashSchema,actor:ActorSchema4,member_count:MemberCountSchema,auto:AutoSchema}).strict()});var exports_team_disband={};__export(exports_team_disband,{schema:()=>schema35,TYPE:()=>TYPE34,SCHEMA_VERSION:()=>SCHEMA_VERSION34,KIND:()=>KIND34,DEFAULT_TIER:()=>DEFAULT_TIER6});var SCHEMA_VERSION34=1,TYPE34="team.disband",KIND34="event",DEFAULT_TIER6="audit",TeamNameSchema2,ActorSchema5,RemainingMembersSchema,ReasonSchema8,schema35;var init_team_disband=__esm(()=>{init_zod();init_redactors();TeamNameSchema2=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"),schema35=exports_external.object({team_name:TeamNameSchema2,actor:ActorSchema5,remaining_members:RemainingMembersSchema,reason:ReasonSchema8}).strict()});var exports_tmux_pane_placed={};__export(exports_tmux_pane_placed,{schema:()=>schema36,TYPE:()=>TYPE35,SCHEMA_VERSION:()=>SCHEMA_VERSION35,KIND:()=>KIND35});var SCHEMA_VERSION35=1,TYPE35="tmux.pane.placed",KIND35="event",AgentIdSchema7,SessionSchema,WindowIndexSchema,PaneIndexSchema,PaneIdSchema,ActionSchema,schema36;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"),schema36=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:()=>schema37,TYPE:()=>TYPE36,SCHEMA_VERSION:()=>SCHEMA_VERSION36,KIND:()=>KIND36});var SCHEMA_VERSION36=1,TYPE36="wish.dispatch",KIND36="span",WishSlugSchema2,WaveSchema,GroupIdSchema,GroupNameSchema,ActorSchema6,OutcomeSchema3,DurationSchema7,DryRunSchema,schema37;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"),schema37=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_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),[TYPE36]: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),[TYPE31]:entry(exports_state_transition),[TYPE28]:entry(exports_schema_violation),[TYPE29]:entry(exports_session_id_written),[TYPE30]:entry(exports_session_reconciled),[TYPE35]:entry(exports_tmux_pane_placed),[TYPE17]:entry(exports_executor_row_written),[TYPE5]:entry(exports_cache_invalidate),[TYPE4]:entry(exports_cache_hit),[TYPE27]:entry(exports_runbook_triggered),[TYPE7]:entry(exports_consumer_heartbeat),[TYPE23]:entry(exports_permissions_grant),[TYPE22]:entry(exports_permissions_deny),[TYPE33]:entry(exports_team_create),[TYPE34]: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),[TYPE32]: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),[TYPE26]:entry(exports_rot_team_ls_drift_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 existsSync13,fsyncSync,mkdirSync as mkdirSync7,openSync,readFileSync as readFileSync8,renameSync as renameSync2,statSync,unlinkSync as unlinkSync4}from"fs";import{homedir as homedir12}from"os";import{dirname as dirname4,join as join15}from"path";function getEmitStats(){return{...stats,queue_depth:queue.length}}function defaultSpillPath(){let home=process.env.GENIE_HOME??join15(homedir12(),".genie");return join15(home,"data","emit-spill.jsonl")}function __setSpillPathForTests(path2){spillPathOverride=path2}function spillPath(){return spillPathOverride??defaultSpillPath()}function ensureSpillDir(path2){let dir=dirname4(path2);if(!existsSync13(dir))mkdirSync7(dir,{recursive:!0})}function writeSpillRow(row){let path2=spillPath();ensureSpillDir(path2);let line=`${JSON.stringify(row)}
489
+ `)),"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_team_ls_drift_detected={};__export(exports_rot_team_ls_drift_detected,{schema:()=>schema28,TYPE:()=>TYPE27,SCHEMA_VERSION:()=>SCHEMA_VERSION27,KIND:()=>KIND27});var SCHEMA_VERSION27=1,TYPE27="rot.team-ls-drift.detected",KIND27="event",DivergenceKindSchema,DivergentCountSchema,ObservedStateJsonSchema,schema28;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"),schema28=exports_external.object({divergence_kind:DivergenceKindSchema,divergent_count:DivergentCountSchema,observed_state_json:ObservedStateJsonSchema}).strict()});var exports_runbook_triggered={};__export(exports_runbook_triggered,{schema:()=>schema29,TYPE:()=>TYPE28,SCHEMA_VERSION:()=>SCHEMA_VERSION28,KIND:()=>KIND28});var SCHEMA_VERSION28=1,TYPE28="runbook.triggered",KIND28="event",RuleSchema,EvidenceCountSchema,CorrelationIdSchema,WindowMinutesSchema,RecommendedSqlSchema,EvidenceSummarySchema,schema29;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"),schema29=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:()=>schema30,TYPE:()=>TYPE29,SCHEMA_VERSION:()=>SCHEMA_VERSION29,KIND:()=>KIND29});var SCHEMA_VERSION29=1,TYPE29="schema.violation",KIND29="event",OffendingTypeSchema2,RejectedBytesSchema,IssueSchema,schema30;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"),schema30=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:()=>schema31,TYPE:()=>TYPE30,SCHEMA_VERSION:()=>SCHEMA_VERSION30,KIND:()=>KIND30});var SCHEMA_VERSION30=1,TYPE30="session.id.written",KIND30="event",AgentIdSchema5,SessionIdSchema3,ExecutorSchema4,OriginSchema,DiffSchema2,schema31;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"),schema31=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:()=>schema32,TYPE:()=>TYPE31,SCHEMA_VERSION:()=>SCHEMA_VERSION31,KIND:()=>KIND31});var SCHEMA_VERSION31=1,TYPE31="session.reconciled",KIND31="event",AgentIdSchema6,SessionIdSchema4,ReasonSchema6,DiffSchema3,schema32;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"),schema32=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:()=>schema33,TYPE:()=>TYPE32,SCHEMA_VERSION:()=>SCHEMA_VERSION32,KIND:()=>KIND32});var SCHEMA_VERSION32=1,TYPE32="state_transition",KIND32="event",EntityKindSchema,EntityIdSchema2,FromSchema2,ToSchema2,ReasonSchema7,ActorSchema3,DiffSchema4,schema33;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"),schema33=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:()=>schema34,TYPE:()=>TYPE33,SCHEMA_VERSION:()=>SCHEMA_VERSION33,KIND:()=>KIND33});var SCHEMA_VERSION33=1,TYPE33="stream.gap.detected",KIND33="event",ConsumerIdSchema2,IdSchema,CountSchema6,schema34;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"),schema34=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:()=>schema35,TYPE:()=>TYPE34,SCHEMA_VERSION:()=>SCHEMA_VERSION34,KIND:()=>KIND34,DEFAULT_TIER:()=>DEFAULT_TIER5});var SCHEMA_VERSION34=1,TYPE34="team.create",KIND34="event",DEFAULT_TIER5="audit",TeamNameSchema,WishSlugSchema,RepoPathHashSchema,ActorSchema4,MemberCountSchema,AutoSchema,schema35;var init_team_create=__esm(()=>{init_zod();init_redactors();TeamNameSchema=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"),schema35=exports_external.object({team_name:TeamNameSchema,wish_slug:WishSlugSchema,repo_path_hash:RepoPathHashSchema,actor:ActorSchema4,member_count:MemberCountSchema,auto:AutoSchema}).strict()});var exports_team_disband={};__export(exports_team_disband,{schema:()=>schema36,TYPE:()=>TYPE35,SCHEMA_VERSION:()=>SCHEMA_VERSION35,KIND:()=>KIND35,DEFAULT_TIER:()=>DEFAULT_TIER6});var SCHEMA_VERSION35=1,TYPE35="team.disband",KIND35="event",DEFAULT_TIER6="audit",TeamNameSchema2,ActorSchema5,RemainingMembersSchema,ReasonSchema8,schema36;var init_team_disband=__esm(()=>{init_zod();init_redactors();TeamNameSchema2=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"),schema36=exports_external.object({team_name:TeamNameSchema2,actor:ActorSchema5,remaining_members:RemainingMembersSchema,reason:ReasonSchema8}).strict()});var exports_tmux_pane_placed={};__export(exports_tmux_pane_placed,{schema:()=>schema37,TYPE:()=>TYPE36,SCHEMA_VERSION:()=>SCHEMA_VERSION36,KIND:()=>KIND36});var SCHEMA_VERSION36=1,TYPE36="tmux.pane.placed",KIND36="event",AgentIdSchema7,SessionSchema,WindowIndexSchema,PaneIndexSchema,PaneIdSchema,ActionSchema,schema37;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"),schema37=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:()=>schema38,TYPE:()=>TYPE37,SCHEMA_VERSION:()=>SCHEMA_VERSION37,KIND:()=>KIND37});var SCHEMA_VERSION37=1,TYPE37="wish.dispatch",KIND37="span",WishSlugSchema2,WaveSchema,GroupIdSchema,GroupNameSchema,ActorSchema6,OutcomeSchema3,DurationSchema7,DryRunSchema,schema38;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"),schema38=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_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),[TYPE37]: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),[TYPE32]:entry(exports_state_transition),[TYPE29]:entry(exports_schema_violation),[TYPE30]:entry(exports_session_id_written),[TYPE31]:entry(exports_session_reconciled),[TYPE36]:entry(exports_tmux_pane_placed),[TYPE17]:entry(exports_executor_row_written),[TYPE5]:entry(exports_cache_invalidate),[TYPE4]:entry(exports_cache_hit),[TYPE28]:entry(exports_runbook_triggered),[TYPE7]:entry(exports_consumer_heartbeat),[TYPE23]:entry(exports_permissions_grant),[TYPE22]:entry(exports_permissions_deny),[TYPE34]:entry(exports_team_create),[TYPE35]: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),[TYPE33]: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),[TYPE27]:entry(exports_rot_team_ls_drift_detected),[TYPE26]:entry(exports_rot_executor_ghost_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 existsSync13,fsyncSync,mkdirSync as mkdirSync7,openSync,readFileSync as readFileSync8,renameSync as renameSync2,statSync,unlinkSync as unlinkSync4}from"fs";import{homedir as homedir12}from"os";import{dirname as dirname4,join as join15}from"path";function getEmitStats(){return{...stats,queue_depth:queue.length}}function defaultSpillPath(){let home=process.env.GENIE_HOME??join15(homedir12(),".genie");return join15(home,"data","emit-spill.jsonl")}function __setSpillPathForTests(path2){spillPathOverride=path2}function spillPath(){return spillPathOverride??defaultSpillPath()}function ensureSpillDir(path2){let dir=dirname4(path2);if(!existsSync13(dir))mkdirSync7(dir,{recursive:!0})}function writeSpillRow(row){let path2=spillPath();ensureSpillDir(path2);let line=`${JSON.stringify(row)}
490
490
  `,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(!existsSync13(path2))return 0;try{let contents=readFileSync8(path2,"utf8");if(!contents)return 0;return contents.split(`
491
491
  `).filter((l)=>l.length>0).length}catch{return 0}}function isSpillJournalEmpty(){return countSpillRows()===0}function readStagingRows(staging){let contents;try{contents=readFileSync8(staging,"utf8")}catch{return[]}let lines=contents.split(`
492
492
  `).filter((l)=>l.length>0),rows=[];for(let line of lines)try{rows.push(JSON.parse(line))}catch{}return rows}function reappendRowsToJournal(path2,rows){let fd=openSync(path2,"a");try{for(let row of rows)appendFileSync(fd,`${JSON.stringify(row)}
493
493
  `);try{fsyncSync(fd)}catch{}}finally{closeSync(fd)}}function stageSpillJournal(path2){let size=0;try{size=statSync(path2).size}catch{return null}if(size===0)return null;let staging=`${path2}.draining-${process.pid}`;try{renameSync2(path2,staging)}catch{return null}return staging}async function drainSpillJournal(){let path2=spillPath();if(!existsSync13(path2))return 0;let staging=stageSpillJournal(path2);if(!staging)return 0;let rows=readStagingRows(staging);if(rows.length===0){try{unlinkSync4(staging)}catch{}return 0}try{await writeBatch(rows),stats.flushed+=rows.length}catch(err){return reappendRowsToJournal(path2,rows),process.stderr.write(`[emit] spill drain retry pending: ${err instanceof Error?err.message:String(err)}
494
494
  `),0}try{unlinkSync4(staging)}catch{}return firstSpillAt=null,stats.backpressure_active=!1,rows.length}function startSpan(type2,attrs={},opts={}){let entry2=getEntry(type2),kind=entry2?.kind??"span";if(entry2&&kind!=="span")emitSchemaViolation(type2,`startSpan called on '${kind}' type`);let ctx=opts.ctx??{},span_id=newId();return{type:type2,trace_id:ctx.trace_id??newTraceId2(),span_id,parent_span_id:ctx.span_id??ctx.parent_span_id,started_at:Date.now(),start_attrs:attrs,severity:opts.severity??"info",source_subsystem:opts.source_subsystem}}function endSpan(handle,attrs={},opts={}){let duration_ms=Date.now()-handle.started_at,merged={...handle.start_attrs,...attrs,duration_ms};enqueueTyped(handle.type,merged,{severity:opts.severity??handle.severity,source_subsystem:opts.source_subsystem??handle.source_subsystem,ctx:{trace_id:handle.trace_id,span_id:handle.span_id,parent_span_id:handle.parent_span_id},repo_path:opts.repo_path,agent:opts.agent,team:opts.team,entity_id:opts.entity_id},duration_ms)}function emitEvent(type2,payload,opts={}){let entry2=getEntry(type2);if(entry2&&entry2.kind==="span"){emitSchemaViolation(type2,"emitEvent called on 'span' type \u2014 use start/endSpan");return}enqueueTyped(type2,payload,opts,null)}function parsePayload(entry2,type2,payload){if(!entry2)return null;try{let result2=entry2.schema.safeParse(payload);if(!result2.success)return stats.schema_violations++,emitSchemaViolation(type2,"zod parse failure",result2.error.issues),null;return result2.data}catch(err){return stats.schema_violations++,emitSchemaViolation(type2,`zod throw: ${err instanceof Error?err.message:String(err)}`),null}}function classifyAdmission(severity){if(queue.length<QUEUE_CAP)return{action:"admit"};if(severity==="debug")return stats.dropped_debug++,{action:"drop",reason:"debug"};if(severity==="info")return{action:"drop",reason:"info"};return{action:"spill"}}function buildRow(type2,entry2,payload,severity,duration_ms,opts){let ctx=opts.ctx??{};return{type:type2,kind:entry2.kind,schema_version:entry2.schema_version,tier_defaults:entry2.tier_defaults,trace_id:ctx.trace_id??newTraceId2(),span_id:ctx.span_id??newId(),parent_span_id:ctx.parent_span_id??null,severity,source_subsystem:opts.source_subsystem??null,dedup_key:computeDedupKey(type2,opts.entity_id??"",payload),duration_ms,repo_path:opts.repo_path??process.env.GENIE_REPO_PATH??process.cwd(),agent:opts.agent??process.env.GENIE_AGENT_NAME??"system",team:opts.team??process.env.GENIE_TEAM??null,detector_version:opts.detector_version??null,payload,created_at:new Date().toISOString()}}function preparePayload(type2,payload){let entry2=getEntry(type2);if(!entry2)return null;let parsed=parsePayload(entry2,type2,payload);if(!parsed)return null;let capped=capPayload(parsed);if(capped.overflow)stats.dropped_overflow++;return{entry:entry2,effectivePayload:capped.body}}function handleInfoBackpressure(row,t0){if(stats.dropped_info++,Date.now()-t0<BACKPRESSURE_WAIT_MS&&queue.length<QUEUE_CAP)admitToQueue(row)}function handleSpillPath(row,severity){if(queue.length<QUEUE_CAP){admitToQueue(row);return}try{writeSpillRow(row),stats.backpressure_active=!0,raiseLaggedIfNeeded(severity,row),maybeRaiseBackpressureCritical()}catch(err){process.stderr.write(`[emit] spill write failed (event lost): ${err instanceof Error?err.message:String(err)}
495
- `),stats.dropped_overflow++}}function dispatchDecision(row,severity,decision,t0){if(decision.action==="admit"){admitToQueue(row);return}if(decision.action==="drop"){if(decision.reason==="info")handleInfoBackpressure(row,t0);return}handleSpillPath(row,severity)}function enqueueTyped(type2,payload,opts,duration_ms){let t0=Date.now();if(shuttingDown){stats.dropped_overflow++;return}if(!isRegistered(type2)){emitSchemaViolation(type2,"unregistered event type"),recordLatency(Date.now()-t0);return}let prepared=preparePayload(type2,payload);if(!prepared){recordLatency(Date.now()-t0);return}let severity=opts.severity??"info",row=buildRow(type2,prepared.entry,prepared.effectivePayload,severity,duration_ms,opts);dispatchDecision(row,severity,classifyAdmission(severity),t0),recordLatency(Date.now()-t0)}function admitToQueue(row){if(queue.push(row),stats.enqueued++,stats.queue_depth=queue.length,trackCorrelationSample(row),ensureFlusher(),ensureWatchers(),queue.length>=BATCH_SIZE)triggerFlush()}function recordLatency(ms){if(latencySamples[latencyIdx]=ms,latencyIdx=(latencyIdx+1)%LATENCY_WINDOW,latencyFilled<LATENCY_WINDOW)latencyFilled++;if(latencyFilled===LATENCY_WINDOW&&latencyIdx===0){let p=computePercentiles();enqueueMetaEvent("emitter.latency_p99",{window_samples:latencyFilled,p50_ms:p.p50,p95_ms:p.p95,p99_ms:p.p99,max_ms:p.max})}}function computePercentiles(){let copy=latencySamples.slice(0,latencyFilled).slice().sort((a,b2)=>a-b2),pick=(pct)=>copy.length===0?0:copy[Math.min(copy.length-1,Math.floor(copy.length*pct))];return{p50:pick(0.5),p95:pick(0.95),p99:pick(0.99),max:copy.length===0?0:copy[copy.length-1]}}function trackCorrelationSample(row){if(knownSpanIds.size>=KNOWN_SPAN_CAP){let firstKey=knownSpanIds.values().next().value;if(firstKey)knownSpanIds.delete(firstKey)}knownSpanIds.add(row.span_id);let matched=row.parent_span_id?knownSpanIds.has(row.parent_span_id):!0;if(corrWindow.push({parent_span_id:row.parent_span_id,matched}),corrWindow.length>LATENCY_WINDOW)corrWindow.shift()}function emitSchemaViolation(offendingType,reason,issues){if(offendingType===TYPE28)return;let issueArray=Array.isArray(issues)?issues.slice(0,32).map((i2)=>({path:i2.path.join(".")||"<root>",code:String(i2.code??"unknown"),message:String(i2.message??reason).slice(0,512)})):[{path:"<root>",code:"emit_rejected",message:reason.slice(0,512)}];enqueueTyped(TYPE28,{offending_type:offendingType.slice(0,128),issues:issueArray,rejected_bytes:0},{severity:"warn",source_subsystem:"emit.ts"},null),enqueueMetaEvent("emitter.rejected",{offending_type:offendingType.slice(0,128),reason:"schema_parse",count:1})}function enqueueMetaEvent(type2,payload){if(!isRegistered(type2))return;let entry2=getEntry(type2);if(!entry2)return;let parsed=entry2.schema.safeParse(payload);if(!parsed.success)return;if(queue.length>=QUEUE_CAP)return;let row=buildRow(type2,entry2,parsed.data,"info",null,{source_subsystem:"emit.ts"});queue.push(row),stats.enqueued++,stats.queue_depth=queue.length}function raiseLaggedIfNeeded(severity,_row){if(severity!=="warn"&&severity!=="error"&&severity!=="fatal")return;enqueueMetaEvent("consumer.lagged",{severity_class:severity,spill_path:spillPath(),rows_spilled:1,queue_depth:queue.length,queue_cap:QUEUE_CAP})}function maybeRaiseBackpressureCritical(){if(firstSpillAt===null)return;let duration=Date.now()-firstSpillAt;if(duration<BACKPRESSURE_CRITICAL_MS)return;if(Date.now()-lastCriticalAt<60000)return;lastCriticalAt=Date.now(),enqueueMetaEvent("emit.backpressure.critical",{spill_duration_seconds:Math.round(duration/1000),spill_rows_total:stats.spilled_warn_plus,queue_depth:queue.length,queue_cap:QUEUE_CAP,recommended_action:"inspect_pg"})}function computeDedupKey(type2,entityId,payload){let minuteBucket=Math.floor(Date.now()/60000),digest="";try{digest=createHash2("sha256").update(JSON.stringify(payload)).digest("hex").slice(0,16)}catch{digest="nohash"}return createHash2("sha256").update(`${type2}|${entityId}|${digest}|${minuteBucket}`).digest("hex").slice(0,32)}function newTraceId2(){return randomUUID4().replace(/-/g,"")}function newId(){return randomUUID4().replace(/-/g,"").slice(0,16)}function ensureFlusher(){if(flushTimer)return;if(flushTimer=setInterval(()=>{triggerFlush()},FLUSH_INTERVAL_MS),typeof flushTimer.unref==="function")flushTimer.unref()}function ensureWatchers(){if(watchersStartedAt!==0)return;if(watchersStartedAt=Date.now(),queueDepthTimer=setInterval(()=>{stats.spill_rows_pending=countSpillRows(),enqueueMetaEvent("emitter.queue.depth",{depth:queue.length,cap:QUEUE_CAP,utilization:queue.length/QUEUE_CAP,enqueued_total:stats.enqueued,flushed_total:stats.flushed})},QUEUE_DEPTH_TICK_MS),typeof queueDepthTimer.unref==="function")queueDepthTimer.unref();if(sheddingTimer=setInterval(()=>{if(stats.dropped_debug===0&&stats.dropped_info===0&&stats.spilled_warn_plus===0)return;enqueueMetaEvent("emitter.shedding_load",{dropped_debug:stats.dropped_debug,dropped_info:stats.dropped_info,spilled_warn_plus:stats.spilled_warn_plus,window_seconds:Math.round(SHEDDING_SUMMARY_MS/1000)})},SHEDDING_SUMMARY_MS),typeof sheddingTimer.unref==="function")sheddingTimer.unref();if(correlationTimer=setInterval(()=>{if(corrWindow.length<100)return;let orphans=corrWindow.reduce((acc,e)=>acc+(e.parent_span_id&&!e.matched?1:0),0),rate=orphans/corrWindow.length;enqueueMetaEvent("correlation.orphan.rate",{window_samples:corrWindow.length,orphans,rate})},QUEUE_DEPTH_TICK_MS),typeof correlationTimer.unref==="function")correlationTimer.unref()}function triggerFlush(){if(flushInFlight)return flushInFlight;if(queue.length===0)return Promise.resolve();return flushInFlight=doFlush().finally(()=>{flushInFlight=null}),flushInFlight}async function doFlush(){if(queue.length===0)return;let batch=queue.splice(0,BATCH_SIZE),t0=Date.now();try{if(await writeBatch(batch),stats.flushed+=batch.length,stats.last_flush_rows=batch.length,stats.last_flush_ms=Date.now()-t0,!isSpillJournalEmpty())drainSpillJournal()}catch(err){let reinjectCap=Math.max(0,QUEUE_CAP-queue.length);if(reinjectCap>0)queue.unshift(...batch.slice(0,reinjectCap));process.stderr.write(`[emit] flush failed: ${err instanceof Error?err.message:String(err)} (requeued ${Math.min(batch.length,reinjectCap)}/${batch.length})
495
+ `),stats.dropped_overflow++}}function dispatchDecision(row,severity,decision,t0){if(decision.action==="admit"){admitToQueue(row);return}if(decision.action==="drop"){if(decision.reason==="info")handleInfoBackpressure(row,t0);return}handleSpillPath(row,severity)}function enqueueTyped(type2,payload,opts,duration_ms){let t0=Date.now();if(shuttingDown){stats.dropped_overflow++;return}if(!isRegistered(type2)){emitSchemaViolation(type2,"unregistered event type"),recordLatency(Date.now()-t0);return}let prepared=preparePayload(type2,payload);if(!prepared){recordLatency(Date.now()-t0);return}let severity=opts.severity??"info",row=buildRow(type2,prepared.entry,prepared.effectivePayload,severity,duration_ms,opts);dispatchDecision(row,severity,classifyAdmission(severity),t0),recordLatency(Date.now()-t0)}function admitToQueue(row){if(queue.push(row),stats.enqueued++,stats.queue_depth=queue.length,trackCorrelationSample(row),ensureFlusher(),ensureWatchers(),queue.length>=BATCH_SIZE)triggerFlush()}function recordLatency(ms){if(latencySamples[latencyIdx]=ms,latencyIdx=(latencyIdx+1)%LATENCY_WINDOW,latencyFilled<LATENCY_WINDOW)latencyFilled++;if(latencyFilled===LATENCY_WINDOW&&latencyIdx===0){let p=computePercentiles();enqueueMetaEvent("emitter.latency_p99",{window_samples:latencyFilled,p50_ms:p.p50,p95_ms:p.p95,p99_ms:p.p99,max_ms:p.max})}}function computePercentiles(){let copy=latencySamples.slice(0,latencyFilled).slice().sort((a,b2)=>a-b2),pick=(pct)=>copy.length===0?0:copy[Math.min(copy.length-1,Math.floor(copy.length*pct))];return{p50:pick(0.5),p95:pick(0.95),p99:pick(0.99),max:copy.length===0?0:copy[copy.length-1]}}function trackCorrelationSample(row){if(knownSpanIds.size>=KNOWN_SPAN_CAP){let firstKey=knownSpanIds.values().next().value;if(firstKey)knownSpanIds.delete(firstKey)}knownSpanIds.add(row.span_id);let matched=row.parent_span_id?knownSpanIds.has(row.parent_span_id):!0;if(corrWindow.push({parent_span_id:row.parent_span_id,matched}),corrWindow.length>LATENCY_WINDOW)corrWindow.shift()}function emitSchemaViolation(offendingType,reason,issues){if(offendingType===TYPE29)return;let issueArray=Array.isArray(issues)?issues.slice(0,32).map((i2)=>({path:i2.path.join(".")||"<root>",code:String(i2.code??"unknown"),message:String(i2.message??reason).slice(0,512)})):[{path:"<root>",code:"emit_rejected",message:reason.slice(0,512)}];enqueueTyped(TYPE29,{offending_type:offendingType.slice(0,128),issues:issueArray,rejected_bytes:0},{severity:"warn",source_subsystem:"emit.ts"},null),enqueueMetaEvent("emitter.rejected",{offending_type:offendingType.slice(0,128),reason:"schema_parse",count:1})}function enqueueMetaEvent(type2,payload){if(!isRegistered(type2))return;let entry2=getEntry(type2);if(!entry2)return;let parsed=entry2.schema.safeParse(payload);if(!parsed.success)return;if(queue.length>=QUEUE_CAP)return;let row=buildRow(type2,entry2,parsed.data,"info",null,{source_subsystem:"emit.ts"});queue.push(row),stats.enqueued++,stats.queue_depth=queue.length}function raiseLaggedIfNeeded(severity,_row){if(severity!=="warn"&&severity!=="error"&&severity!=="fatal")return;enqueueMetaEvent("consumer.lagged",{severity_class:severity,spill_path:spillPath(),rows_spilled:1,queue_depth:queue.length,queue_cap:QUEUE_CAP})}function maybeRaiseBackpressureCritical(){if(firstSpillAt===null)return;let duration=Date.now()-firstSpillAt;if(duration<BACKPRESSURE_CRITICAL_MS)return;if(Date.now()-lastCriticalAt<60000)return;lastCriticalAt=Date.now(),enqueueMetaEvent("emit.backpressure.critical",{spill_duration_seconds:Math.round(duration/1000),spill_rows_total:stats.spilled_warn_plus,queue_depth:queue.length,queue_cap:QUEUE_CAP,recommended_action:"inspect_pg"})}function computeDedupKey(type2,entityId,payload){let minuteBucket=Math.floor(Date.now()/60000),digest="";try{digest=createHash2("sha256").update(JSON.stringify(payload)).digest("hex").slice(0,16)}catch{digest="nohash"}return createHash2("sha256").update(`${type2}|${entityId}|${digest}|${minuteBucket}`).digest("hex").slice(0,32)}function newTraceId2(){return randomUUID4().replace(/-/g,"")}function newId(){return randomUUID4().replace(/-/g,"").slice(0,16)}function ensureFlusher(){if(flushTimer)return;if(flushTimer=setInterval(()=>{triggerFlush()},FLUSH_INTERVAL_MS),typeof flushTimer.unref==="function")flushTimer.unref()}function ensureWatchers(){if(watchersStartedAt!==0)return;if(watchersStartedAt=Date.now(),queueDepthTimer=setInterval(()=>{stats.spill_rows_pending=countSpillRows(),enqueueMetaEvent("emitter.queue.depth",{depth:queue.length,cap:QUEUE_CAP,utilization:queue.length/QUEUE_CAP,enqueued_total:stats.enqueued,flushed_total:stats.flushed})},QUEUE_DEPTH_TICK_MS),typeof queueDepthTimer.unref==="function")queueDepthTimer.unref();if(sheddingTimer=setInterval(()=>{if(stats.dropped_debug===0&&stats.dropped_info===0&&stats.spilled_warn_plus===0)return;enqueueMetaEvent("emitter.shedding_load",{dropped_debug:stats.dropped_debug,dropped_info:stats.dropped_info,spilled_warn_plus:stats.spilled_warn_plus,window_seconds:Math.round(SHEDDING_SUMMARY_MS/1000)})},SHEDDING_SUMMARY_MS),typeof sheddingTimer.unref==="function")sheddingTimer.unref();if(correlationTimer=setInterval(()=>{if(corrWindow.length<100)return;let orphans=corrWindow.reduce((acc,e)=>acc+(e.parent_span_id&&!e.matched?1:0),0),rate=orphans/corrWindow.length;enqueueMetaEvent("correlation.orphan.rate",{window_samples:corrWindow.length,orphans,rate})},QUEUE_DEPTH_TICK_MS),typeof correlationTimer.unref==="function")correlationTimer.unref()}function triggerFlush(){if(flushInFlight)return flushInFlight;if(queue.length===0)return Promise.resolve();return flushInFlight=doFlush().finally(()=>{flushInFlight=null}),flushInFlight}async function doFlush(){if(queue.length===0)return;let batch=queue.splice(0,BATCH_SIZE),t0=Date.now();try{if(await writeBatch(batch),stats.flushed+=batch.length,stats.last_flush_rows=batch.length,stats.last_flush_ms=Date.now()-t0,!isSpillJournalEmpty())drainSpillJournal()}catch(err){let reinjectCap=Math.max(0,QUEUE_CAP-queue.length);if(reinjectCap>0)queue.unshift(...batch.slice(0,reinjectCap));process.stderr.write(`[emit] flush failed: ${err instanceof Error?err.message:String(err)} (requeued ${Math.min(batch.length,reinjectCap)}/${batch.length})
496
496
  `)}stats.queue_depth=queue.length}async function flushNow(){await triggerFlush();while(queue.length>0&&!shuttingDown)await triggerFlush()}async function drainSpillJournalNow(){return drainSpillJournal()}async function shutdownEmitter(){if(shuttingDown=!0,flushTimer)clearInterval(flushTimer),flushTimer=null;if(queueDepthTimer)clearInterval(queueDepthTimer),queueDepthTimer=null;if(sheddingTimer)clearInterval(sheddingTimer),sheddingTimer=null;if(correlationTimer)clearInterval(correlationTimer),correlationTimer=null;watchersStartedAt=0;try{while(queue.length>0)await triggerFlush()}finally{shuttingDown=!1}}function routeTable(row){if(row.tier_defaults==="audit")return"audit";if(row.tier_defaults==="debug")return"debug";if(row.severity==="debug"){let sampleByte=Number.parseInt(row.dedup_key.slice(-2),16);if(!Number.isNaN(sampleByte)&&sampleByte%100===0)return"main";return"debug"}return"main"}function rowRecord(row){let enrichedData={...row.payload,_trace_id:row.trace_id,_span_id:row.span_id,_parent_span_id:row.parent_span_id,_severity:row.severity,_schema_version:row.schema_version,_duration_ms:row.duration_ms,_dedup_key:row.dedup_key,_source_subsystem:row.source_subsystem,_tier:row.tier_defaults,_kind:row.kind};return{repo_path:row.repo_path,subject:row.type,kind:"system",source:"sdk",agent:row.agent,team:row.team,direction:null,peer:null,text:row.type,data:enrichedData,detector_version:row.detector_version,created_at:row.created_at}}async function writeBatch(batch){let sql=await getConnection(),buckets={main:[],debug:[],audit:[]};for(let row of batch)buckets[routeTable(row)].push(row);let writeBucket=async(table,rows)=>{if(rows.length===0)return;for(let row of rows){let rec=rowRecord(row),data=rec.data;if(table==="genie_runtime_events")await sql`
497
497
  INSERT INTO genie_runtime_events
498
498
  (repo_path, subject, kind, source, agent, team, direction, peer, text, data, detector_version, created_at)
@@ -2612,23 +2612,33 @@ ${label} <TODO>
2612
2612
  ${p.actor},
2613
2613
  ${tx.json({agent_id:p.agentId,outcome:p.outcome,reason:p.reason})}
2614
2614
  )
2615
- `}async function turnClose(opts){if((opts.outcome==="blocked"||opts.outcome==="failed")&&!opts.reason?.trim())throw Error(`turnClose: --reason is required for outcome '${opts.outcome}'`);let executorId=resolveExecutorId(opts),actor=opts.actor??process.env.GENIE_AGENT_NAME??"cli",reason=opts.reason?.trim()||null,auditInsert=opts.auditInsert??defaultAuditInsert;return(await getConnection()).begin(async(tx)=>{let rows=await tx`
2615
+ `}async function turnClose(opts){if((opts.outcome==="blocked"||opts.outcome==="failed")&&!opts.reason?.trim())throw Error(`turnClose: --reason is required for outcome '${opts.outcome}'`);let executorId=resolveExecutorId(opts),actor=opts.actor??process.env.GENIE_AGENT_NAME??"cli",reason=opts.reason?.trim()||null,auditInsert=opts.auditInsert??defaultAuditInsert;return(await getConnection()).begin(async(tx)=>{let effectiveId=executorId,rows=await tx`
2616
2616
  SELECT state, outcome, agent_id FROM executors
2617
2617
  WHERE id = ${executorId}
2618
2618
  FOR UPDATE
2619
- `;if(rows.length===0)throw Error(`turnClose: executor ${executorId} not found`);let row=rows[0];if(row.outcome!==null||TERMINAL_STATES.has(row.state))return{noop:!0,executorId,outcome:row.outcome??opts.outcome,closedAt:null};let now=new Date().toISOString();return await tx`
2619
+ `;if(rows.length===0){let agentName=process.env.GENIE_AGENT_NAME;if(agentName){let fallback=await tx`
2620
+ SELECT id FROM executors
2621
+ WHERE agent_id = ${agentName}
2622
+ ORDER BY started_at DESC
2623
+ LIMIT 1
2624
+ FOR UPDATE
2625
+ `;if(fallback.length>0){effectiveId=fallback[0].id,rows=await tx`
2626
+ SELECT state, outcome, agent_id FROM executors
2627
+ WHERE id = ${effectiveId}
2628
+ FOR UPDATE
2629
+ `,console.warn(`[turn-close] executor ${executorId} not found, falling back to agent_id='${agentName}' \u2192 ${effectiveId}`);try{emitEvent("rot.executor-ghost.detected",{resolution_source:"resolver",env_id:executorId,resolved_id:effectiveId,agent_name:agentName,recovered:!0},{severity:"warn",source_subsystem:"turn-close"})}catch{}}}if(rows.length===0)throw Error(`turnClose: executor ${executorId} not found (no fallback by agent_id='${agentName??""}')`)}let row=rows[0];if(row.outcome!==null||TERMINAL_STATES.has(row.state))return{noop:!0,executorId:effectiveId,outcome:row.outcome??opts.outcome,closedAt:null};let now=new Date().toISOString();return await tx`
2620
2630
  UPDATE executors
2621
2631
  SET outcome = ${opts.outcome},
2622
2632
  closed_at = ${now},
2623
2633
  close_reason = ${reason},
2624
2634
  state = 'done',
2625
2635
  ended_at = ${now}
2626
- WHERE id = ${executorId}
2636
+ WHERE id = ${effectiveId}
2627
2637
  `,await tx`
2628
2638
  UPDATE agents
2629
2639
  SET current_executor_id = NULL
2630
- WHERE current_executor_id = ${executorId}
2631
- `,await auditInsert(tx,{executorId,agentId:row.agent_id,outcome:opts.outcome,reason,actor}),{noop:!1,executorId,outcome:opts.outcome,closedAt:now}})}var TERMINAL_STATES;var init_turn_close=__esm(()=>{init_db();TERMINAL_STATES=new Set(["done","terminated","error"])});var exports_done={};__export(exports_done,{doneAction:()=>doneAction});async function doneAction(ref,deps={}){let agentName=process.env.GENIE_AGENT_NAME;if(!ref&&agentName){let result2=await(deps.turnCloseFn??turnClose)({outcome:"done"});if(result2.noop)console.log(`\u2139\uFE0F Executor ${result2.executorId} already closed \u2014 no-op.`);else console.log(`\u2705 Turn closed: outcome=done, executor=${result2.executorId}`);return}if(ref){await(deps.wishDone??(async(r)=>{let{doneCommand:doneCommand2}=await Promise.resolve().then(() => (init_state(),exports_state));await doneCommand2(r)}))(ref);return}console.error("\u274C genie done requires either a <slug>#<group> ref (team-lead) or GENIE_AGENT_NAME (inside agent session)."),process.exit(2)}var init_done=__esm(()=>{init_turn_close()});var exports_blocked={};__export(exports_blocked,{blockedAction:()=>blockedAction});async function blockedAction(options,deps={}){let reason=options.reason?.trim();if(!reason)console.error('\u274C genie blocked requires --reason "<message>"'),process.exit(2);let result2=await(deps.turnCloseFn??turnClose)({outcome:"blocked",reason});if(result2.noop)console.log(`\u2139\uFE0F Executor ${result2.executorId} already closed \u2014 no-op.`);else console.log(`\uD83D\uDD12 Turn closed: outcome=blocked, executor=${result2.executorId}`),console.log(` Reason: ${reason}`)}var init_blocked=__esm(()=>{init_turn_close()});var exports_failed={};__export(exports_failed,{failedAction:()=>failedAction});async function failedAction(options,deps={}){let reason=options.reason?.trim();if(!reason)console.error('\u274C genie failed requires --reason "<message>"'),process.exit(2);let result2=await(deps.turnCloseFn??turnClose)({outcome:"failed",reason});if(result2.noop)console.log(`\u2139\uFE0F Executor ${result2.executorId} already closed \u2014 no-op.`);else console.log(`\uD83D\uDED1 Turn closed: outcome=failed, executor=${result2.executorId}`),console.log(` Reason: ${reason}`)}var init_failed=__esm(()=>{init_turn_close()});async function resolveExecutorId2(sql,opts){if(opts.executorId)return{id:opts.executorId,source:"executorId"};if(opts.paneId){let rows=await sql`
2640
+ WHERE current_executor_id = ${effectiveId}
2641
+ `,await auditInsert(tx,{executorId:effectiveId,agentId:row.agent_id,outcome:opts.outcome,reason,actor}),{noop:!1,executorId:effectiveId,outcome:opts.outcome,closedAt:now}})}var TERMINAL_STATES;var init_turn_close=__esm(()=>{init_db();init_emit();TERMINAL_STATES=new Set(["done","terminated","error"])});var exports_done={};__export(exports_done,{doneAction:()=>doneAction});async function doneAction(ref,deps={}){let agentName=process.env.GENIE_AGENT_NAME;if(!ref&&agentName){let result2=await(deps.turnCloseFn??turnClose)({outcome:"done"});if(result2.noop)console.log(`\u2139\uFE0F Executor ${result2.executorId} already closed \u2014 no-op.`);else console.log(`\u2705 Turn closed: outcome=done, executor=${result2.executorId}`);return}if(ref){await(deps.wishDone??(async(r)=>{let{doneCommand:doneCommand2}=await Promise.resolve().then(() => (init_state(),exports_state));await doneCommand2(r)}))(ref);return}console.error("\u274C genie done requires either a <slug>#<group> ref (team-lead) or GENIE_AGENT_NAME (inside agent session)."),process.exit(2)}var init_done=__esm(()=>{init_turn_close()});var exports_blocked={};__export(exports_blocked,{blockedAction:()=>blockedAction});async function blockedAction(options,deps={}){let reason=options.reason?.trim();if(!reason)console.error('\u274C genie blocked requires --reason "<message>"'),process.exit(2);let result2=await(deps.turnCloseFn??turnClose)({outcome:"blocked",reason});if(result2.noop)console.log(`\u2139\uFE0F Executor ${result2.executorId} already closed \u2014 no-op.`);else console.log(`\uD83D\uDD12 Turn closed: outcome=blocked, executor=${result2.executorId}`),console.log(` Reason: ${reason}`)}var init_blocked=__esm(()=>{init_turn_close()});var exports_failed={};__export(exports_failed,{failedAction:()=>failedAction});async function failedAction(options,deps={}){let reason=options.reason?.trim();if(!reason)console.error('\u274C genie failed requires --reason "<message>"'),process.exit(2);let result2=await(deps.turnCloseFn??turnClose)({outcome:"failed",reason});if(result2.noop)console.log(`\u2139\uFE0F Executor ${result2.executorId} already closed \u2014 no-op.`);else console.log(`\uD83D\uDED1 Turn closed: outcome=failed, executor=${result2.executorId}`),console.log(` Reason: ${reason}`)}var init_failed=__esm(()=>{init_turn_close()});async function resolveExecutorId2(sql,opts){if(opts.executorId)return{id:opts.executorId,source:"executorId"};if(opts.paneId){let rows=await sql`
2632
2642
  SELECT id FROM executors
2633
2643
  WHERE tmux_pane_id = ${opts.paneId}
2634
2644
  ORDER BY started_at DESC
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@automagik/genie",
3
- "version": "4.260421.3",
3
+ "version": "4.260421.5",
4
4
  "description": "Collaborative terminal toolkit for human + AI workflows",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "genie",
3
- "version": "4.260421.3",
3
+ "version": "4.260421.5",
4
4
  "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.",
5
5
  "author": {
6
6
  "name": "Namastex Labs"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "genie-plugin",
3
- "version": "4.260421.3",
3
+ "version": "4.260421.5",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for genie bundled CLIs",
6
6
  "type": "module",