@automagik/genie 4.260429.23 → 4.260429.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/genie.js
CHANGED
|
@@ -422,7 +422,7 @@ ${bin} set-option -w pane-active-border-style "fg=$COLOR"
|
|
|
422
422
|
WHERE (${includeArchived} OR state IS DISTINCT FROM 'archived')
|
|
423
423
|
`;return rows.map(rowToAgentIdentity)}async function listAgentsForRender(filters){let all=await listAgents(filters);return dedupeShadowRows(all,{keyFor:(a)=>shadowKey(a.customName,a.id,a.team),hasExecutor:(a)=>a.currentExecutorId!=null,startedAt:(a)=>a.startedAt})}async function auditAgentKind(){let rows=await(await getConnection())`
|
|
424
424
|
SELECT id, kind, reports_to FROM agents
|
|
425
|
-
`,drifted=[];for(let row of rows){let expected=row.id.startsWith("dir:")||row.reports_to===null?"permanent":"task";if(row.kind!==expected)drifted.push({id:row.id,kind:row.kind,expected})}for(let drift of drifted)recordAuditEvent("worker",drift.id,"agents.kind.audit_drift","auditor",{stored:drift.kind,expected:drift.expected}).catch(()=>{});return{total:rows.length,drifted}}var DEAD_PANE_ZOMBIE_TTL_HOURS=24;var init_agent_registry=__esm(()=>{init_audit();init_db();init_tmux()});function ts2(v){if(!v)return new Date().toISOString();return v instanceof Date?v.toISOString():v}function rowToExecutor(r){return{id:r.id,agentId:r.agent_id,provider:r.provider,transport:r.transport,pid:r.pid,tmuxSession:r.tmux_session,tmuxPaneId:r.tmux_pane_id,tmuxWindow:r.tmux_window,tmuxWindowId:r.tmux_window_id,claudeSessionId:r.claude_session_id,state:r.state,metadata:typeof r.metadata==="string"?JSON.parse(r.metadata):r.metadata??{},worktree:r.worktree,repoPath:r.repo_path,paneColor:r.pane_color,startedAt:ts2(r.started_at),endedAt:r.ended_at?ts2(r.ended_at):null,createdAt:ts2(r.created_at),updatedAt:ts2(r.updated_at),turnId:r.turn_id??null,outcome:r.outcome??null,closedAt:r.closed_at?ts2(r.closed_at):null,closeReason:r.close_reason??null}}function rowToAssignment(r){return{id:r.id,executorId:r.executor_id,taskId:r.task_id,wishSlug:r.wish_slug,groupNumber:r.group_number,startedAt:ts2(r.started_at),endedAt:r.ended_at?ts2(r.ended_at):null,outcome:r.outcome,createdAt:ts2(r.created_at)}}var exports_executor_registry={};__export(exports_executor_registry,{updateExecutorState:()=>updateExecutorState,updateClaudeSessionId:()=>updateClaudeSessionId,terminateExecutor:()=>terminateExecutor,terminateActiveExecutor:()=>terminateActiveExecutor,resolveWorkerLivenessByTransport:()=>resolveWorkerLivenessByTransport,relinkExecutorToAgent:()=>relinkExecutorToAgent,recordResumeProviderRejected:()=>recordResumeProviderRejected,listExecutors:()=>listExecutors,isExecutorAlive:()=>isExecutorAlive,getResumeSessionId:()=>getResumeSessionId,getLiveExecutorState:()=>getLiveExecutorState,getExecutor:()=>getExecutor,getCurrentExecutor:()=>getCurrentExecutor,findLatestByMetadata:()=>findLatestByMetadata,findExecutorBySession:()=>findExecutorBySession,findExecutorByPane:()=>findExecutorByPane,createExecutor:()=>createExecutor,createAndLinkExecutor:()=>createAndLinkExecutor,_resumeJsonlScannerDeps:()=>_resumeJsonlScannerDeps,_resetMissingSessionDedupeForTests:()=>_resetMissingSessionDedupeForTests});import{randomUUID as randomUUID2}from"crypto";import{open,readdir,stat}from"fs/promises";import{homedir as homedir7}from"os";import{join as join13}from"path";async function createExecutor(agentId,provider,transport,opts={}){let sql=await getConnection(),id=opts.id??randomUUID2(),now=new Date().toISOString(),rows=await sql`
|
|
425
|
+
`,drifted=[];for(let row of rows){let expected=row.id.startsWith("dir:")||row.reports_to===null?"permanent":"task";if(row.kind!==expected)drifted.push({id:row.id,kind:row.kind,expected})}for(let drift of drifted)recordAuditEvent("worker",drift.id,"agents.kind.audit_drift","auditor",{stored:drift.kind,expected:drift.expected}).catch(()=>{});return{total:rows.length,drifted}}var DEAD_PANE_ZOMBIE_TTL_HOURS=24;var init_agent_registry=__esm(()=>{init_audit();init_db();init_tmux()});function ts2(v){if(!v)return new Date().toISOString();return v instanceof Date?v.toISOString():v}function rowToExecutor(r){return{id:r.id,agentId:r.agent_id,provider:r.provider,transport:r.transport,pid:r.pid,tmuxSession:r.tmux_session,tmuxPaneId:r.tmux_pane_id,tmuxWindow:r.tmux_window,tmuxWindowId:r.tmux_window_id,claudeSessionId:r.claude_session_id,state:r.state,metadata:typeof r.metadata==="string"?JSON.parse(r.metadata):r.metadata??{},worktree:r.worktree,repoPath:r.repo_path,paneColor:r.pane_color,startedAt:ts2(r.started_at),endedAt:r.ended_at?ts2(r.ended_at):null,createdAt:ts2(r.created_at),updatedAt:ts2(r.updated_at),turnId:r.turn_id??null,outcome:r.outcome??null,closedAt:r.closed_at?ts2(r.closed_at):null,closeReason:r.close_reason??null}}function rowToAssignment(r){return{id:r.id,executorId:r.executor_id,taskId:r.task_id,wishSlug:r.wish_slug,groupNumber:r.group_number,startedAt:ts2(r.started_at),endedAt:r.ended_at?ts2(r.ended_at):null,outcome:r.outcome,createdAt:ts2(r.created_at)}}var exports_executor_registry={};__export(exports_executor_registry,{updateExecutorState:()=>updateExecutorState,updateClaudeSessionId:()=>updateClaudeSessionId,terminateExecutor:()=>terminateExecutor,terminateActiveExecutor:()=>terminateActiveExecutor,resolveWorkerLivenessByTransport:()=>resolveWorkerLivenessByTransport,relinkExecutorToAgent:()=>relinkExecutorToAgent,recordResumeProviderRejected:()=>recordResumeProviderRejected,recordResumeMissingSession:()=>recordResumeMissingSession,listExecutors:()=>listExecutors,isExecutorAlive:()=>isExecutorAlive,getResumeSessionId:()=>getResumeSessionId,getLiveExecutorState:()=>getLiveExecutorState,getExecutor:()=>getExecutor,getCurrentExecutor:()=>getCurrentExecutor,findLatestByMetadata:()=>findLatestByMetadata,findExecutorBySession:()=>findExecutorBySession,findExecutorByPane:()=>findExecutorByPane,createExecutor:()=>createExecutor,createAndLinkExecutor:()=>createAndLinkExecutor,_resumeJsonlScannerDeps:()=>_resumeJsonlScannerDeps,_resetMissingSessionDedupeForTests:()=>_resetMissingSessionDedupeForTests});import{randomUUID as randomUUID2}from"crypto";import{open,readdir,stat}from"fs/promises";import{homedir as homedir7}from"os";import{join as join13}from"path";async function createExecutor(agentId,provider,transport,opts={}){let sql=await getConnection(),id=opts.id??randomUUID2(),now=new Date().toISOString(),rows=await sql`
|
|
426
426
|
INSERT INTO executors (
|
|
427
427
|
id, agent_id, provider, transport, pid,
|
|
428
428
|
tmux_session, tmux_pane_id, tmux_window, tmux_window_id,
|
|
@@ -477,7 +477,7 @@ ${bin} set-option -w pane-active-border-style "fg=$COLOR"
|
|
|
477
477
|
ORDER BY started_at DESC
|
|
478
478
|
LIMIT 1
|
|
479
479
|
`;return rows.length>0?rowToExecutor(rows[0]):null}async function relinkExecutorToAgent(executorId,agentId){await(await getConnection())`UPDATE agents SET current_executor_id = ${executorId} WHERE id = ${agentId}`}async function updateClaudeSessionId(executorId,sessionId){await(await getConnection())`UPDATE executors SET claude_session_id = ${sessionId} WHERE id = ${executorId}`}function sanitizeCwdForProjects(p){return p.replace(/[^a-zA-Z0-9]/g,"-")}function resolveClaudeConfigDir(){return process.env.CLAUDE_CONFIG_DIR??join13(homedir7(),".claude")}async function readJsonlIdentity(filePath){let handle=null;try{handle=await open(filePath,"r");let buffer=Buffer.alloc(16384),{bytesRead}=await handle.read(buffer,0,buffer.length,0),head=buffer.toString("utf-8",0,bytesRead);for(let line of head.split(`
|
|
480
|
-
`).slice(0,40)){let trimmed=line.trim();if(!trimmed)continue;try{let entry=JSON.parse(trimmed),teamName=typeof entry.teamName==="string"?entry.teamName:null,agentName=typeof entry.agentName==="string"?entry.agentName:null;if(teamName!==null&&agentName!==null)return{teamName,agentName}}catch{}}}catch{return{teamName:null,agentName:null}}finally{await handle?.close().catch(()=>{})}return{teamName:null,agentName:null}}async function mapWithConcurrency(items,cap,fn){let results=Array(items.length),cursor=0,workers=[],workerCount=Math.min(cap,items.length);for(let w=0;w<workerCount;w++)workers.push((async()=>{while(cursor<items.length){let i2=cursor++;if(i2>=items.length)return;results[i2]=await fn(items[i2])}})());return await Promise.all(workers),results}async function defaultScanForSession(cwd,identity){if(!identity)return null;let projectDir=join13(resolveClaudeConfigDir(),"projects",sanitizeCwdForProjects(cwd)),entries;try{entries=await readdir(projectDir)}catch{return null}let jsonls=entries.filter((e)=>e.endsWith(".jsonl"));if(jsonls.length===0)return null;let sorted=(await mapWithConcurrency(jsonls,STAT_CONCURRENCY_CAP,async(name)=>{let full=join13(projectDir,name);try{let s=await stat(full);return{name,full,mtime:s.mtimeMs}}catch{return null}})).filter((x)=>x!==null).sort((a,b)=>b.mtime-a.mtime);for(let candidate of sorted){let{teamName,agentName}=await readJsonlIdentity(candidate.full);if(teamName!==identity.team||agentName!==identity.customName)continue;return candidate.name.replace(/\.jsonl$/,"")}return null}async function tryJsonlFallback(agentId,row,actor){let cwd=row?.repo_path??null;if(!cwd)return null;let team=row?.team??null,customName=row?.custom_name??null,identity=team&&customName?{team,customName}:null;if(!identity)return null;let recoveredSessionId=await(_resumeJsonlScannerDeps.scanForSession??defaultScanForSession)(cwd,identity);if(!recoveredSessionId)return null;let reason=row&&row.executor_id!==null?"null_session":"no_executor";return await recordAuditEvent("agent",agentId,"resume.recovered_via_jsonl",actor,{sessionId:recoveredSessionId,executorId:row?.executor_id??null,cwd,team:identity.team,customName:identity.customName,recoveredFrom:reason}),recoveredSessionId}function
|
|
480
|
+
`).slice(0,40)){let trimmed=line.trim();if(!trimmed)continue;try{let entry=JSON.parse(trimmed),teamName=typeof entry.teamName==="string"?entry.teamName:null,agentName=typeof entry.agentName==="string"?entry.agentName:null;if(teamName!==null&&agentName!==null)return{teamName,agentName}}catch{}}}catch{return{teamName:null,agentName:null}}finally{await handle?.close().catch(()=>{})}return{teamName:null,agentName:null}}async function mapWithConcurrency(items,cap,fn){let results=Array(items.length),cursor=0,workers=[],workerCount=Math.min(cap,items.length);for(let w=0;w<workerCount;w++)workers.push((async()=>{while(cursor<items.length){let i2=cursor++;if(i2>=items.length)return;results[i2]=await fn(items[i2])}})());return await Promise.all(workers),results}async function defaultScanForSession(cwd,identity){if(!identity)return null;let projectDir=join13(resolveClaudeConfigDir(),"projects",sanitizeCwdForProjects(cwd)),entries;try{entries=await readdir(projectDir)}catch{return null}let jsonls=entries.filter((e)=>e.endsWith(".jsonl"));if(jsonls.length===0)return null;let sorted=(await mapWithConcurrency(jsonls,STAT_CONCURRENCY_CAP,async(name)=>{let full=join13(projectDir,name);try{let s=await stat(full);return{name,full,mtime:s.mtimeMs}}catch{return null}})).filter((x)=>x!==null).sort((a,b)=>b.mtime-a.mtime);for(let candidate of sorted){let{teamName,agentName}=await readJsonlIdentity(candidate.full);if(teamName!==identity.team||agentName!==identity.customName)continue;return candidate.name.replace(/\.jsonl$/,"")}return null}async function tryJsonlFallback(agentId,row,actor){let cwd=row?.repo_path??null;if(!cwd)return null;let team=row?.team??null,customName=row?.custom_name??null,identity=team&&customName?{team,customName}:null;if(!identity)return null;let recoveredSessionId=await(_resumeJsonlScannerDeps.scanForSession??defaultScanForSession)(cwd,identity);if(!recoveredSessionId)return null;let reason=row&&row.executor_id!==null?"null_session":"no_executor";return await recordAuditEvent("agent",agentId,"resume.recovered_via_jsonl",actor,{sessionId:recoveredSessionId,executorId:row?.executor_id??null,cwd,team:identity.team,customName:identity.customName,recoveredFrom:reason}),recoveredSessionId}function _resetMissingSessionDedupeForTests(){}async function recordResumeMissingSession(agentId,actor,details){await recordAuditEvent("agent",agentId,"resume.missing_session",actor,details)}async function getResumeSessionId(agentId){let rows=await(await getConnection())`
|
|
481
481
|
SELECT a.current_executor_id AS executor_id,
|
|
482
482
|
e.claude_session_id,
|
|
483
483
|
a.repo_path,
|
|
@@ -486,13 +486,13 @@ ${bin} set-option -w pane-active-border-style "fg=$COLOR"
|
|
|
486
486
|
FROM agents a
|
|
487
487
|
LEFT JOIN executors e ON e.id = a.current_executor_id
|
|
488
488
|
WHERE a.id = ${agentId}
|
|
489
|
-
`,actor=process.env.GENIE_AGENT_NAME??"cli",row=rows[0]??null;if(row&&row.executor_id!==null&&row.claude_session_id)return await recordAuditEvent("agent",agentId,"resume.found",actor,{executorId:row.executor_id,sessionId:row.claude_session_id}),row.claude_session_id;let recovered=await tryJsonlFallback(agentId,row,actor);if(recovered)return recovered;return
|
|
489
|
+
`,actor=process.env.GENIE_AGENT_NAME??"cli",row=rows[0]??null;if(row&&row.executor_id!==null&&row.claude_session_id)return await recordAuditEvent("agent",agentId,"resume.found",actor,{executorId:row.executor_id,sessionId:row.claude_session_id}),row.claude_session_id;let recovered=await tryJsonlFallback(agentId,row,actor);if(recovered)return recovered;return null}async function recordResumeProviderRejected(agentId,sessionId,reason){await recordAuditEvent("agent",agentId,"resume.provider_rejected",process.env.GENIE_AGENT_NAME??"cli",{sessionId,reason})}async function getLiveExecutorState(agentId){let rows=await(await getConnection())`
|
|
490
490
|
SELECT e.state FROM executors e
|
|
491
491
|
JOIN agents a ON a.current_executor_id = e.id
|
|
492
492
|
WHERE a.id = ${agentId}
|
|
493
493
|
AND e.state IN ('spawning', 'running', 'working', 'idle', 'permission', 'question')
|
|
494
494
|
LIMIT 1
|
|
495
|
-
`;return rows.length>0?rows[0].state:null}async function isExecutorAlive(agentId){return await getLiveExecutorState(agentId)!==null}async function resolveWorkerLivenessByTransport(worker,opts){if(/^%\d+$/.test(worker.paneId))return(opts?.isPaneAliveFn??(async(pane)=>{let{isPaneAlive:isPaneAlive2}=await Promise.resolve().then(() => (init_tmux(),exports_tmux));return isPaneAlive2(pane)}))(worker.paneId);return(opts?.isExecutorAliveFn??isExecutorAlive)(worker.id)}var STAT_CONCURRENCY_CAP=32,_resumeJsonlScannerDeps
|
|
495
|
+
`;return rows.length>0?rows[0].state:null}async function isExecutorAlive(agentId){return await getLiveExecutorState(agentId)!==null}async function resolveWorkerLivenessByTransport(worker,opts){if(/^%\d+$/.test(worker.paneId))return(opts?.isPaneAliveFn??(async(pane)=>{let{isPaneAlive:isPaneAlive2}=await Promise.resolve().then(() => (init_tmux(),exports_tmux));return isPaneAlive2(pane)}))(worker.paneId);return(opts?.isExecutorAliveFn??isExecutorAlive)(worker.id)}var STAT_CONCURRENCY_CAP=32,_resumeJsonlScannerDeps;var init_executor_registry=__esm(()=>{init_audit();init_db();_resumeJsonlScannerDeps={scanForSession:null}});var exports_team_manager={};__export(exports_team_manager,{validateBranchName:()=>validateBranchName,updateTeamConfig:()=>updateTeamConfig,unarchiveTeam:()=>unarchiveTeam,setTeamStatus:()=>setTeamStatus,resolveLeaderName:()=>resolveLeaderName,listTeams:()=>listTeams,listMembers:()=>listMembers,killTeamMembers:()=>killTeamMembers,hireAgent:()=>hireAgent,getTeam:()=>getTeam,fireAgent:()=>fireAgent,ensureTeamRow:()=>ensureTeamRow,disbandTeam:()=>disbandTeam,createTeam:()=>createTeam,archiveTeam:()=>archiveTeam});import{existsSync as existsSync10}from"fs";import{mkdir as mkdir2,rm,symlink}from"fs/promises";import{homedir as homedir8}from"os";import path,{join as join14}from"path";var{$:$2}=globalThis.Bun;function parseMembers(raw){if(Array.isArray(raw))return raw;if(typeof raw==="string")try{let parsed=JSON.parse(raw);return Array.isArray(parsed)?parsed:[]}catch{return[]}return[]}function rowToTeamConfig(row){let config={name:row.name,repo:row.repo,baseBranch:row.base_branch,worktreePath:row.worktree_path,members:parseMembers(row.members),status:row.status,createdAt:row.created_at instanceof Date?row.created_at.toISOString():String(row.created_at)};if(row.leader)config.leader=row.leader;if(row.native_team_parent_session_id)config.nativeTeamParentSessionId=row.native_team_parent_session_id;if(row.native_teams_enabled)config.nativeTeamsEnabled=row.native_teams_enabled;if(row.tmux_session_name)config.tmuxSessionName=row.tmux_session_name;if(row.wish_slug)config.wishSlug=row.wish_slug;if(row.spawner)config.spawner=row.spawner;if(row.archived_at)config.archivedAt=row.archived_at instanceof Date?row.archived_at.toISOString():String(row.archived_at);if(row.parent_team)config.parentTeam=row.parent_team;let allow=parseAllowChildReachback(row.allow_child_reachback);if(allow.length>0)config.allowChildReachback=allow;return config}function parseAllowChildReachback(raw){if(Array.isArray(raw))return raw.filter((x)=>typeof x==="string");if(typeof raw==="string")try{let parsed=JSON.parse(raw);return Array.isArray(parsed)?parsed.filter((x)=>typeof x==="string"):[]}catch{return[]}return[]}function getGenieDir2(){return process.env.GENIE_HOME??join14(homedir8(),".genie")}function getWorktreeBase(repoPath){let base=loadGenieConfigSync().terminal?.worktreeBase;if(base&&base!==".worktrees"){if(path.isAbsolute(base))return base;return join14(repoPath,base)}let projectName=path.basename(repoPath);return join14(getGenieDir2(),"worktrees",projectName)}function validateBranchName(name){let errors2=[];if(/\s/.test(name))errors2.push("contains spaces");if(name.includes(".."))errors2.push('contains ".."');if(name.includes("~"))errors2.push('contains "~"');if(name.includes("^"))errors2.push('contains "^"');if(name.includes(":"))errors2.push('contains ":"');if(name.includes("?"))errors2.push('contains "?"');if(name.includes("*"))errors2.push('contains "*"');if(name.includes("["))errors2.push('contains "["');if(name.includes("\\"))errors2.push('contains "\\"');if(/[\x00-\x1f\x7f]/.test(name))errors2.push("contains control characters");if(name.endsWith(".lock"))errors2.push('ends with ".lock"');if(name.endsWith("/"))errors2.push('ends with "/"');if(name.endsWith("."))errors2.push('ends with "."');if(name.startsWith("-"))errors2.push('starts with "-"');if(errors2.length>0)throw Error(`Invalid team name '${name}': must be a valid git branch name (${errors2.join(", ")})`)}async function killWorkersByName(agentName,teamName){let matches=(await list()).filter((w)=>(w.role===agentName||w.id===agentName)&&(!teamName||w.team===teamName));for(let w of matches){if(w.currentExecutorId)try{await terminateExecutor(w.currentExecutorId),await setCurrentExecutor(w.id,null)}catch{}try{if(w.paneId&&w.paneId!=="inline"){let{execSync:execSync2}=__require("child_process"),{genieTmuxCmd:genieTmuxCmd2}=(init_tmux_wrapper(),__toCommonJS(exports_tmux_wrapper));execSync2(genieTmuxCmd2(`kill-pane -t ${w.paneId}`),{stdio:"ignore"})}}catch{}await unregister(w.id)}}async function postCloneInit(repoPath,worktreePath){let parentNodeModules=join14(repoPath,"node_modules"),worktreeNodeModules=join14(worktreePath,"node_modules");if(existsSync10(parentNodeModules)&&!existsSync10(worktreeNodeModules))try{await symlink(parentNodeModules,worktreeNodeModules,"dir")}catch{}let initScript=join14(repoPath,".genie","init.sh");if(existsSync10(initScript))try{await $2`bash ${initScript}`.cwd(worktreePath).quiet()}catch{}}async function ensureWorktree(repoPath,branchName,worktreePath,baseBranch){try{await $2`git -C ${repoPath} fetch origin ${baseBranch}`.quiet()}catch{}if(await mkdir2(path.dirname(worktreePath),{recursive:!0}),existsSync10(worktreePath))return;let branchExists=!1;try{await $2`git -C ${repoPath} rev-parse --verify ${branchName}`.quiet(),branchExists=!0}catch{if(!branchExists)try{await $2`git -C ${repoPath} branch ${branchName} origin/${baseBranch}`.quiet()}catch{try{await $2`git -C ${repoPath} branch ${branchName} ${baseBranch}`.quiet()}catch{await $2`git -C ${repoPath} branch ${branchName}`.quiet()}}}await $2`git clone --shared --branch ${branchName} ${repoPath} ${worktreePath}`.quiet();try{let userName=(await $2`git -C ${repoPath} config user.name`.quiet()).text().trim(),userEmail=(await $2`git -C ${repoPath} config user.email`.quiet()).text().trim();if(userName)await $2`git -C ${worktreePath} config user.name ${userName}`.quiet();if(userEmail)await $2`git -C ${worktreePath} config user.email ${userEmail}`.quiet()}catch{}await postCloneInit(repoPath,worktreePath)}async function detectSpawnerParentTeam(newTeamName){let envTeam=process.env.GENIE_TEAM,spawnerName=process.env.GENIE_AGENT_NAME;if(!envTeam||!spawnerName)return null;if(spawnerName==="cli")return null;if(envTeam===newTeamName)return null;try{return await getTeam(envTeam)?envTeam:null}catch{return null}}async function createTeam(name,repo,baseBranch="dev"){validateBranchName(name);let repoPath=path.resolve(repo),existing=await getTeam(name);if(existing)return existing;let worktreeBase=getWorktreeBase(repoPath),worktreePath=join14(worktreeBase,name);await ensureWorktree(repoPath,name,worktreePath,baseBranch);let now=new Date().toISOString(),config={name,repo:repoPath,baseBranch,worktreePath,members:[],status:"in_progress",createdAt:now},promoted=await detectSpawnerParentTeam(name);if(promoted)config.parentTeam=promoted;if(isInsideClaudeCode()){config.nativeTeamsEnabled=!0;try{let result2=await registerAsTeamLead(name);config.nativeTeamParentSessionId=result2.sessionId}catch{}}return await(await getConnection())`
|
|
496
496
|
INSERT INTO teams (
|
|
497
497
|
name, repo, base_branch, worktree_path, leader,
|
|
498
498
|
members, status, native_team_parent_session_id,
|
|
@@ -675,13 +675,13 @@ ${bin} set-option -w pane-active-border-style "fg=$COLOR"
|
|
|
675
675
|
tell.location
|
|
676
676
|
from (select lo_tell64($1) as location) tell
|
|
677
677
|
) seek
|
|
678
|
-
`};return resolve3(lo),new Promise(async(r)=>finish=r);async function readable({highWaterMark=16384,start=0,end=1/0}={}){let max=end-start;return start&&await lo.seek(start),new Stream2.Readable({highWaterMark,async read(size){let l=size>max?size-max:size;max-=size;let[{data}]=await lo.read(l);if(this.push(data),data.length<size)this.push(null)}})}async function writable({highWaterMark=16384,start=0}={}){return start&&await lo.seek(start),new Stream2.Writable({highWaterMark,write(chunk,encoding,callback){lo.write(chunk).then(()=>callback(),callback)}})}}).catch(reject)})}var init_large=()=>{};var exports_src={};__export(exports_src,{default:()=>src_default});import os from"os";import fs from"fs";function Postgres(a,b2){let options=parseOptions(a,b2),subscribe=options.no_subscribe||Subscribe(Postgres,{...options}),ending=!1,queries=queue_default(),connecting=queue_default(),reserved=queue_default(),closed=queue_default(),ended=queue_default(),open3=queue_default(),busy=queue_default(),full=queue_default(),queues={connecting,reserved,closed,ended,open:open3,busy,full},connections=[...Array(options.max)].map(()=>connection_default(options,queues,{onopen,onend,onclose})),sql=Sql(handler);return Object.assign(sql,{get parameters(){return options.parameters},largeObject:largeObject.bind(null,sql),subscribe,CLOSE,END:CLOSE,PostgresError,options,reserve,listen,begin,close,end}),sql;function Sql(handler2){return handler2.debug=options.debug,Object.entries(options.types).reduce((acc,[name,type2])=>{return acc[name]=(x)=>new Parameter(x,type2.to),acc},typed),Object.assign(sql2,{types:typed,typed,unsafe,notify,array,json:json2,file}),sql2;function typed(value,type2){return new Parameter(value,type2)}function sql2(strings,...args){return strings&&Array.isArray(strings.raw)?new Query(strings,args,handler2,cancel):typeof strings==="string"&&!args.length?new Identifier(options.transform.column.to?options.transform.column.to(strings):strings):new Builder(strings,args)}function unsafe(string,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([string],args,handler2,cancel,{prepare:!1,...options2,simple:"simple"in options2?options2.simple:args.length===0})}function file(path2,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([],args,(query2)=>{fs.readFile(path2,"utf8",(err,string)=>{if(err)return query2.reject(err);query2.strings=[string],handler2(query2)})},cancel,{...options2,simple:"simple"in options2?options2.simple:args.length===0})}}async function listen(name,fn,onlisten){let listener={fn,onlisten},sql2=listen.sql||(listen.sql=Postgres({...options,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(listen.channels).forEach(([name2,{listeners}])=>{delete listen.channels[name2],Promise.all(listeners.map((l)=>listen(name2,l.fn,l.onlisten).catch(()=>{})))})},onnotify(c,x){c in listen.channels&&listen.channels[c].listeners.forEach((l)=>l.fn(x))}})),channels=listen.channels||(listen.channels={});if(name in channels){channels[name].listeners.push(listener);let result3=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result3.state,unlisten}}channels[name]={result:sql2`listen ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`,listeners:[listener]};let result2=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result2.state,unlisten};async function unlisten(){if(name in channels===!1)return;if(channels[name].listeners=channels[name].listeners.filter((x)=>x!==listener),channels[name].listeners.length)return;return delete channels[name],sql2`unlisten ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`}}async function notify(channel,payload){return await sql`select pg_notify(${channel}, ${""+payload})`}async function reserve(){let queue=queue_default(),c=open3.length?open3.shift():await new Promise((resolve3,reject)=>{let query={reserve:resolve3,reject};queries.push(query),closed.length&&connect(closed.shift(),query)});move(c,reserved),c.reserved=()=>queue.length?c.execute(queue.shift()):move(c,reserved),c.reserved.release=!0;let sql2=Sql(handler2);return sql2.release=()=>{c.reserved=null,onopen(c)},sql2;function handler2(q){c.queue===full?queue.push(q):c.execute(q)||move(c,full)}}async function begin(options2,fn){!fn&&(fn=options2,options2="");let queries2=queue_default(),savepoints=0,connection2,prepare=null;try{return await sql.unsafe("begin "+options2.replace(/[^a-z ]/ig,""),[],{onexecute}).execute(),await Promise.race([scope(connection2,fn),new Promise((_,reject)=>connection2.onclose=reject)])}catch(error){throw error}async function scope(c,fn2,name){let sql2=Sql(handler2);sql2.savepoint=savepoint,sql2.prepare=(x)=>prepare=x.replace(/[^a-z0-9$-_. ]/gi);let uncaughtError,result2;name&&await sql2`savepoint ${sql2(name)}`;try{if(result2=await new Promise((resolve3,reject)=>{let x=fn2(sql2);Promise.resolve(Array.isArray(x)?Promise.all(x):x).then(resolve3,reject)}),uncaughtError)throw uncaughtError}catch(e){throw await(name?sql2`rollback to ${sql2(name)}`:sql2`rollback`),e instanceof PostgresError&&e.code==="25P02"&&uncaughtError||e}if(!name)prepare?await sql2`prepare transaction '${sql2.unsafe(prepare)}'`:await sql2`commit`;return result2;function savepoint(name2,fn3){if(name2&&Array.isArray(name2.raw))return savepoint((sql3)=>sql3.apply(sql3,arguments));return arguments.length===1&&(fn3=name2,name2=null),scope(c,fn3,"s"+savepoints+++(name2?"_"+name2:""))}function handler2(q){q.catch((e)=>uncaughtError||(uncaughtError=e)),c.queue===full?queries2.push(q):c.execute(q)||move(c,full)}}function onexecute(c){connection2=c,move(c,reserved),c.reserved=()=>queries2.length?c.execute(queries2.shift()):move(c,reserved)}}function move(c,queue){return c.queue.remove(c),queue.push(c),c.queue=queue,queue===open3?c.idleTimer.start():c.idleTimer.cancel(),c}function json2(x){return new Parameter(x,3802)}function array(x,type2){if(!Array.isArray(x))return array(Array.from(arguments));return new Parameter(x,type2||(x.length?inferType(x)||25:0),options.shared.typeArrayMap)}function handler(query){if(ending)return query.reject(Errors.connection("CONNECTION_ENDED",options,options));if(open3.length)return go(open3.shift(),query);if(closed.length)return connect(closed.shift(),query);busy.length?go(busy.shift(),query):queries.push(query)}function go(c,query){return c.execute(query)?move(c,busy):move(c,full)}function cancel(query){return new Promise((resolve3,reject)=>{query.state?query.active?connection_default(options).cancel(query.state,resolve3,reject):query.cancelled={resolve:resolve3,reject}:(queries.remove(query),query.cancelled=!0,query.reject(Errors.generic("57014","canceling statement due to user request")),resolve3())})}async function end({timeout=null}={}){if(ending)return ending;await 1;let timer2;return ending=Promise.race([new Promise((r)=>timeout!==null&&(timer2=setTimeout(destroy,timeout*1000,r))),Promise.all(connections.map((c)=>c.end()).concat(listen.sql?listen.sql.end({timeout:0}):[],subscribe.sql?subscribe.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(timer2))}async function close(){await Promise.all(connections.map((c)=>c.end()))}async function destroy(resolve3){await Promise.all(connections.map((c)=>c.terminate()));while(queries.length)queries.shift().reject(Errors.connection("CONNECTION_DESTROYED",options));resolve3()}function connect(c,query){return move(c,connecting),c.connect(query),c}function onend(c){move(c,ended)}function onopen(c){if(queries.length===0)return move(c,open3);let max=Math.ceil(queries.length/(connecting.length+1)),ready=!0;while(ready&&queries.length&&max-- >0){let query=queries.shift();if(query.reserve)return query.reserve(c);ready=c.execute(query)}ready?move(c,busy):move(c,full)}function onclose(c,e){move(c,closed),c.reserved=null,c.onclose&&(c.onclose(e),c.onclose=null),options.onclose&&options.onclose(c.id),queries.length&&connect(c,queries.shift())}}function parseOptions(a,b2){if(a&&a.shared)return a;let env=process.env,o=(!a||typeof a==="string"?b2:a)||{},{url,multihost}=parseUrl(a),query=[...url.searchParams].reduce((a2,[b3,c])=>(a2[b3]=c,a2),{}),host=o.hostname||o.host||multihost||url.hostname||env.PGHOST||"localhost",port=o.port||url.port||env.PGPORT||5432,user=o.user||o.username||url.username||env.PGUSERNAME||env.PGUSER||osUsername();o.no_prepare&&(o.prepare=!1),query.sslmode&&(query.ssl=query.sslmode,delete query.sslmode),"timeout"in o&&(console.log("The timeout option is deprecated, use idle_timeout instead"),o.idle_timeout=o.timeout),query.sslrootcert==="system"&&(query.ssl="verify-full");let ints=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],defaults={max:globalThis.Cloudflare?3:10,ssl:!1,sslnegotiation:null,idle_timeout:null,connect_timeout:30,max_lifetime,max_pipeline:100,backoff,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(host)?host:host.split(",").map((x)=>x.split(":")[0]),port:Array.isArray(port)?port:host.split(",").map((x)=>parseInt(x.split(":")[1]||port)),path:o.path||host.indexOf("/")>-1&&host+"/.s.PGSQL."+port,database:o.database||o.db||(url.pathname||"").slice(1)||env.PGDATABASE||user,user,pass:o.pass||o.password||url.password||env.PGPASSWORD||"",...Object.entries(defaults).reduce((acc,[k,d])=>{let value=k in o?o[k]:(k in query)?query[k]==="disable"||query[k]==="false"?!1:query[k]:env["PG"+k.toUpperCase()]||d;return acc[k]=typeof value==="string"&&ints.includes(k)?+value:value,acc},{}),connection:{application_name:env.PGAPPNAME||"postgres.js",...o.connection,...Object.entries(query).reduce((acc,[k,v])=>((k in defaults)||(acc[k]=v),acc),{})},types:o.types||{},target_session_attrs:tsa(o,url,env),onnotice:o.onnotice,onnotify:o.onnotify,onclose:o.onclose,onparameter:o.onparameter,socket:o.socket,transform:parseTransform(o.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...mergeUserTypes(o.types)}}function tsa(o,url,env){let x=o.target_session_attrs||url.searchParams.get("target_session_attrs")||env.PGTARGETSESSIONATTRS;if(!x||["read-write","read-only","primary","standby","prefer-standby"].includes(x))return x;throw Error("target_session_attrs "+x+" is not supported")}function backoff(retries){return(0.5+Math.random()/2)*Math.min(3**retries/100,20)}function max_lifetime(){return 60*(30+Math.random()*30)}function parseTransform(x){return{undefined:x.undefined,column:{from:typeof x.column==="function"?x.column:x.column&&x.column.from,to:x.column&&x.column.to},value:{from:typeof x.value==="function"?x.value:x.value&&x.value.from,to:x.value&&x.value.to},row:{from:typeof x.row==="function"?x.row:x.row&&x.row.from,to:x.row&&x.row.to}}}function parseUrl(url){if(!url||typeof url!=="string")return{url:{searchParams:new Map}};let host=url;host=host.slice(host.indexOf("://")+3).split(/[?/]/)[0],host=decodeURIComponent(host.slice(host.indexOf("@")+1));let urlObj=new URL(url.replace(host,host.split(",")[0]));return{url:{username:decodeURIComponent(urlObj.username),password:decodeURIComponent(urlObj.password),host:urlObj.host,hostname:urlObj.hostname,port:urlObj.port,pathname:urlObj.pathname,searchParams:urlObj.searchParams},multihost:host.indexOf(",")>-1&&host}}function osUsername(){try{return os.userInfo().username}catch(_){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}var src_default;var init_src=__esm(()=>{init_types3();init_connection();init_query();init_queue();init_errors2();init_large();Object.assign(Postgres,{PostgresError,toPascal,pascal,toCamel,camel,toKebab,kebab,fromPascal,fromCamel,fromKebab,BigInt:{to:20,from:[20],parse:(x)=>BigInt(x),serialize:(x)=>x.toString()}});src_default=Postgres});var exports_db={};__export(exports_db,{shutdown:()=>shutdown,runRetention:()=>runRetention,resetConnection:()=>resetConnection,isConnected:()=>isConnected,isAvailable:()=>isAvailable,getLockfilePath:()=>getLockfilePath,getDataDir:()=>getDataDir,getConnection:()=>getConnection,getActivePort:()=>getActivePort,ensurePgserve:()=>ensurePgserve,checkRootGuard:()=>checkRootGuard,autoStartDaemon:()=>autoStartDaemon,__setSpawnDaemonForTest:()=>__setSpawnDaemonForTest});import{execSync as execSync3,spawn}from"child_process";import{existsSync as existsSync13,mkdirSync as mkdirSync6,readFileSync as readFileSync9,renameSync,unlinkSync as unlinkSync3,writeFileSync as writeFileSync6}from"fs";import{homedir as homedir11}from"os";import{join as join17}from"path";function maskCredentials(url){return url.replace(/\/\/.*@/,"//***@")}function checkRootGuard(){if(process.getuid?.()!==0)return null;if(process.env.GENIE_ALLOW_ROOT==="1")return null;return"pgserve cannot start under uid 0 (root) \u2014 PostgreSQL refuses to run as root for security reasons. "+"Run genie as a non-root user, or set GENIE_ALLOW_ROOT=1 to attempt anyway. See: https://github.com/automagik-dev/genie/issues/1226"}function isPgAutostartDisabled(){let value=process.env.GENIE_PG_NO_AUTOSTART;return value!==void 0&&TRUTHY_ENV.has(value.trim().toLowerCase())}function selfHealPostgres(dataDir){try{execSync3(`pkill -9 -f "postgres.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000}),execSync3(`pkill -9 -f "pgserve.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000})}catch{}let pidFile=join17(dataDir,"postmaster.pid");if(existsSync13(pidFile))try{unlinkSync3(pidFile)}catch{}try{execSync3("ipcs -m 2>/dev/null | awk '$6 == 0 {print $2}' | xargs -I{} ipcrm -m {} 2>/dev/null || true",{stdio:"ignore",timeout:5000})}catch{}}function getPort(){let envPort=process.env.GENIE_PG_PORT;if(envPort){let parsed=Number.parseInt(envPort,10);if(!Number.isNaN(parsed)&&parsed>0&&parsed<65536)return parsed}return DEFAULT_PORT}async function isPostgresHealthy(port){try{return await Promise.race([(async()=>{let pg=(await Promise.resolve().then(() => (init_src(),exports_src))).default,probe=pg({host:DEFAULT_HOST,port,database:DB_NAME,username:"postgres",password:"postgres",max:1,connect_timeout:3,idle_timeout:1});try{return await probe`SELECT 1`,await probe.end({timeout:2}),!0}catch{try{await probe.end({timeout:1})}catch{}return!1}})(),new Promise((resolve3)=>{setTimeout(()=>resolve3(!1),4000).unref()})])}catch{return!1}}function readLockfile(){try{let content=readFileSync9(LOCKFILE_PATH,"utf-8").trim(),port=Number.parseInt(content,10);if(!Number.isNaN(port)&&port>0&&port<65536)return port}catch{}return null}function writeLockfile(port){try{mkdirSync6(GENIE_HOME,{recursive:!0});let tmpPath=`${LOCKFILE_PATH}.tmp.${process.pid}`;writeFileSync6(tmpPath,String(port),"utf-8"),renameSync(tmpPath,LOCKFILE_PATH)}catch{}}function removeLockfile(){try{unlinkSync3(LOCKFILE_PATH)}catch{}}async function runRetention(sql){try{await sql.unsafe(`
|
|
678
|
+
`};return resolve3(lo),new Promise(async(r)=>finish=r);async function readable({highWaterMark=16384,start=0,end=1/0}={}){let max=end-start;return start&&await lo.seek(start),new Stream2.Readable({highWaterMark,async read(size){let l=size>max?size-max:size;max-=size;let[{data}]=await lo.read(l);if(this.push(data),data.length<size)this.push(null)}})}async function writable({highWaterMark=16384,start=0}={}){return start&&await lo.seek(start),new Stream2.Writable({highWaterMark,write(chunk,encoding,callback){lo.write(chunk).then(()=>callback(),callback)}})}}).catch(reject)})}var init_large=()=>{};var exports_src={};__export(exports_src,{default:()=>src_default});import os from"os";import fs from"fs";function Postgres(a,b2){let options=parseOptions(a,b2),subscribe=options.no_subscribe||Subscribe(Postgres,{...options}),ending=!1,queries=queue_default(),connecting=queue_default(),reserved=queue_default(),closed=queue_default(),ended=queue_default(),open3=queue_default(),busy=queue_default(),full=queue_default(),queues={connecting,reserved,closed,ended,open:open3,busy,full},connections=[...Array(options.max)].map(()=>connection_default(options,queues,{onopen,onend,onclose})),sql=Sql(handler);return Object.assign(sql,{get parameters(){return options.parameters},largeObject:largeObject.bind(null,sql),subscribe,CLOSE,END:CLOSE,PostgresError,options,reserve,listen,begin,close,end}),sql;function Sql(handler2){return handler2.debug=options.debug,Object.entries(options.types).reduce((acc,[name,type2])=>{return acc[name]=(x)=>new Parameter(x,type2.to),acc},typed),Object.assign(sql2,{types:typed,typed,unsafe,notify,array,json:json2,file}),sql2;function typed(value,type2){return new Parameter(value,type2)}function sql2(strings,...args){return strings&&Array.isArray(strings.raw)?new Query(strings,args,handler2,cancel):typeof strings==="string"&&!args.length?new Identifier(options.transform.column.to?options.transform.column.to(strings):strings):new Builder(strings,args)}function unsafe(string,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([string],args,handler2,cancel,{prepare:!1,...options2,simple:"simple"in options2?options2.simple:args.length===0})}function file(path2,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([],args,(query2)=>{fs.readFile(path2,"utf8",(err,string)=>{if(err)return query2.reject(err);query2.strings=[string],handler2(query2)})},cancel,{...options2,simple:"simple"in options2?options2.simple:args.length===0})}}async function listen(name,fn,onlisten){let listener={fn,onlisten},sql2=listen.sql||(listen.sql=Postgres({...options,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(listen.channels).forEach(([name2,{listeners}])=>{delete listen.channels[name2],Promise.all(listeners.map((l)=>listen(name2,l.fn,l.onlisten).catch(()=>{})))})},onnotify(c,x){c in listen.channels&&listen.channels[c].listeners.forEach((l)=>l.fn(x))}})),channels=listen.channels||(listen.channels={});if(name in channels){channels[name].listeners.push(listener);let result3=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result3.state,unlisten}}channels[name]={result:sql2`listen ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`,listeners:[listener]};let result2=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result2.state,unlisten};async function unlisten(){if(name in channels===!1)return;if(channels[name].listeners=channels[name].listeners.filter((x)=>x!==listener),channels[name].listeners.length)return;return delete channels[name],sql2`unlisten ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`}}async function notify(channel,payload){return await sql`select pg_notify(${channel}, ${""+payload})`}async function reserve(){let queue=queue_default(),c=open3.length?open3.shift():await new Promise((resolve3,reject)=>{let query={reserve:resolve3,reject};queries.push(query),closed.length&&connect(closed.shift(),query)});move(c,reserved),c.reserved=()=>queue.length?c.execute(queue.shift()):move(c,reserved),c.reserved.release=!0;let sql2=Sql(handler2);return sql2.release=()=>{c.reserved=null,onopen(c)},sql2;function handler2(q){c.queue===full?queue.push(q):c.execute(q)||move(c,full)}}async function begin(options2,fn){!fn&&(fn=options2,options2="");let queries2=queue_default(),savepoints=0,connection2,prepare=null;try{return await sql.unsafe("begin "+options2.replace(/[^a-z ]/ig,""),[],{onexecute}).execute(),await Promise.race([scope(connection2,fn),new Promise((_,reject)=>connection2.onclose=reject)])}catch(error){throw error}async function scope(c,fn2,name){let sql2=Sql(handler2);sql2.savepoint=savepoint,sql2.prepare=(x)=>prepare=x.replace(/[^a-z0-9$-_. ]/gi);let uncaughtError,result2;name&&await sql2`savepoint ${sql2(name)}`;try{if(result2=await new Promise((resolve3,reject)=>{let x=fn2(sql2);Promise.resolve(Array.isArray(x)?Promise.all(x):x).then(resolve3,reject)}),uncaughtError)throw uncaughtError}catch(e){throw await(name?sql2`rollback to ${sql2(name)}`:sql2`rollback`),e instanceof PostgresError&&e.code==="25P02"&&uncaughtError||e}if(!name)prepare?await sql2`prepare transaction '${sql2.unsafe(prepare)}'`:await sql2`commit`;return result2;function savepoint(name2,fn3){if(name2&&Array.isArray(name2.raw))return savepoint((sql3)=>sql3.apply(sql3,arguments));return arguments.length===1&&(fn3=name2,name2=null),scope(c,fn3,"s"+savepoints+++(name2?"_"+name2:""))}function handler2(q){q.catch((e)=>uncaughtError||(uncaughtError=e)),c.queue===full?queries2.push(q):c.execute(q)||move(c,full)}}function onexecute(c){connection2=c,move(c,reserved),c.reserved=()=>queries2.length?c.execute(queries2.shift()):move(c,reserved)}}function move(c,queue){return c.queue.remove(c),queue.push(c),c.queue=queue,queue===open3?c.idleTimer.start():c.idleTimer.cancel(),c}function json2(x){return new Parameter(x,3802)}function array(x,type2){if(!Array.isArray(x))return array(Array.from(arguments));return new Parameter(x,type2||(x.length?inferType(x)||25:0),options.shared.typeArrayMap)}function handler(query){if(ending)return query.reject(Errors.connection("CONNECTION_ENDED",options,options));if(open3.length)return go(open3.shift(),query);if(closed.length)return connect(closed.shift(),query);busy.length?go(busy.shift(),query):queries.push(query)}function go(c,query){return c.execute(query)?move(c,busy):move(c,full)}function cancel(query){return new Promise((resolve3,reject)=>{query.state?query.active?connection_default(options).cancel(query.state,resolve3,reject):query.cancelled={resolve:resolve3,reject}:(queries.remove(query),query.cancelled=!0,query.reject(Errors.generic("57014","canceling statement due to user request")),resolve3())})}async function end({timeout=null}={}){if(ending)return ending;await 1;let timer2;return ending=Promise.race([new Promise((r)=>timeout!==null&&(timer2=setTimeout(destroy,timeout*1000,r))),Promise.all(connections.map((c)=>c.end()).concat(listen.sql?listen.sql.end({timeout:0}):[],subscribe.sql?subscribe.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(timer2))}async function close(){await Promise.all(connections.map((c)=>c.end()))}async function destroy(resolve3){await Promise.all(connections.map((c)=>c.terminate()));while(queries.length)queries.shift().reject(Errors.connection("CONNECTION_DESTROYED",options));resolve3()}function connect(c,query){return move(c,connecting),c.connect(query),c}function onend(c){move(c,ended)}function onopen(c){if(queries.length===0)return move(c,open3);let max=Math.ceil(queries.length/(connecting.length+1)),ready=!0;while(ready&&queries.length&&max-- >0){let query=queries.shift();if(query.reserve)return query.reserve(c);ready=c.execute(query)}ready?move(c,busy):move(c,full)}function onclose(c,e){move(c,closed),c.reserved=null,c.onclose&&(c.onclose(e),c.onclose=null),options.onclose&&options.onclose(c.id),queries.length&&connect(c,queries.shift())}}function parseOptions(a,b2){if(a&&a.shared)return a;let env=process.env,o=(!a||typeof a==="string"?b2:a)||{},{url,multihost}=parseUrl(a),query=[...url.searchParams].reduce((a2,[b3,c])=>(a2[b3]=c,a2),{}),host=o.hostname||o.host||multihost||url.hostname||env.PGHOST||"localhost",port=o.port||url.port||env.PGPORT||5432,user=o.user||o.username||url.username||env.PGUSERNAME||env.PGUSER||osUsername();o.no_prepare&&(o.prepare=!1),query.sslmode&&(query.ssl=query.sslmode,delete query.sslmode),"timeout"in o&&(console.log("The timeout option is deprecated, use idle_timeout instead"),o.idle_timeout=o.timeout),query.sslrootcert==="system"&&(query.ssl="verify-full");let ints=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],defaults={max:globalThis.Cloudflare?3:10,ssl:!1,sslnegotiation:null,idle_timeout:null,connect_timeout:30,max_lifetime,max_pipeline:100,backoff,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(host)?host:host.split(",").map((x)=>x.split(":")[0]),port:Array.isArray(port)?port:host.split(",").map((x)=>parseInt(x.split(":")[1]||port)),path:o.path||host.indexOf("/")>-1&&host+"/.s.PGSQL."+port,database:o.database||o.db||(url.pathname||"").slice(1)||env.PGDATABASE||user,user,pass:o.pass||o.password||url.password||env.PGPASSWORD||"",...Object.entries(defaults).reduce((acc,[k,d])=>{let value=k in o?o[k]:(k in query)?query[k]==="disable"||query[k]==="false"?!1:query[k]:env["PG"+k.toUpperCase()]||d;return acc[k]=typeof value==="string"&&ints.includes(k)?+value:value,acc},{}),connection:{application_name:env.PGAPPNAME||"postgres.js",...o.connection,...Object.entries(query).reduce((acc,[k,v])=>((k in defaults)||(acc[k]=v),acc),{})},types:o.types||{},target_session_attrs:tsa(o,url,env),onnotice:o.onnotice,onnotify:o.onnotify,onclose:o.onclose,onparameter:o.onparameter,socket:o.socket,transform:parseTransform(o.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...mergeUserTypes(o.types)}}function tsa(o,url,env){let x=o.target_session_attrs||url.searchParams.get("target_session_attrs")||env.PGTARGETSESSIONATTRS;if(!x||["read-write","read-only","primary","standby","prefer-standby"].includes(x))return x;throw Error("target_session_attrs "+x+" is not supported")}function backoff(retries){return(0.5+Math.random()/2)*Math.min(3**retries/100,20)}function max_lifetime(){return 60*(30+Math.random()*30)}function parseTransform(x){return{undefined:x.undefined,column:{from:typeof x.column==="function"?x.column:x.column&&x.column.from,to:x.column&&x.column.to},value:{from:typeof x.value==="function"?x.value:x.value&&x.value.from,to:x.value&&x.value.to},row:{from:typeof x.row==="function"?x.row:x.row&&x.row.from,to:x.row&&x.row.to}}}function parseUrl(url){if(!url||typeof url!=="string")return{url:{searchParams:new Map}};let host=url;host=host.slice(host.indexOf("://")+3).split(/[?/]/)[0],host=decodeURIComponent(host.slice(host.indexOf("@")+1));let urlObj=new URL(url.replace(host,host.split(",")[0]));return{url:{username:decodeURIComponent(urlObj.username),password:decodeURIComponent(urlObj.password),host:urlObj.host,hostname:urlObj.hostname,port:urlObj.port,pathname:urlObj.pathname,searchParams:urlObj.searchParams},multihost:host.indexOf(",")>-1&&host}}function osUsername(){try{return os.userInfo().username}catch(_){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}var src_default;var init_src=__esm(()=>{init_types3();init_connection();init_query();init_queue();init_errors2();init_large();Object.assign(Postgres,{PostgresError,toPascal,pascal,toCamel,camel,toKebab,kebab,fromPascal,fromCamel,fromKebab,BigInt:{to:20,from:[20],parse:(x)=>BigInt(x),serialize:(x)=>x.toString()}});src_default=Postgres});var exports_db={};__export(exports_db,{shutdown:()=>shutdown,runRetention:()=>runRetention,resetConnection:()=>resetConnection,isConnected:()=>isConnected,isAvailable:()=>isAvailable,getLockfilePath:()=>getLockfilePath,getDataDir:()=>getDataDir,getConnection:()=>getConnection,getActivePort:()=>getActivePort,ensurePgserve:()=>ensurePgserve,checkRootGuard:()=>checkRootGuard,autoStartDaemon:()=>autoStartDaemon,__setSpawnDaemonForTest:()=>__setSpawnDaemonForTest});import{execSync as execSync3,spawn}from"child_process";import{existsSync as existsSync13,mkdirSync as mkdirSync6,readFileSync as readFileSync9,renameSync,unlinkSync as unlinkSync3,writeFileSync as writeFileSync6}from"fs";import{homedir as homedir11}from"os";import{join as join17}from"path";function maskCredentials(url){return url.replace(/\/\/.*@/,"//***@")}function checkRootGuard(){if(process.getuid?.()!==0)return null;if(process.env.GENIE_ALLOW_ROOT==="1")return null;return"pgserve cannot start under uid 0 (root) \u2014 PostgreSQL refuses to run as root for security reasons. "+"Run genie as a non-root user, or set GENIE_ALLOW_ROOT=1 to attempt anyway. See: https://github.com/automagik-dev/genie/issues/1226"}function isPgAutostartDisabled(){let value=process.env.GENIE_PG_NO_AUTOSTART;return value!==void 0&&TRUTHY_ENV.has(value.trim().toLowerCase())}function selfHealPostgres(dataDir){try{execSync3(`pkill -9 -f "postgres.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000}),execSync3(`pkill -9 -f "pgserve.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000})}catch{}let pidFile=join17(dataDir,"postmaster.pid");if(existsSync13(pidFile))try{unlinkSync3(pidFile)}catch{}try{execSync3("ipcs -m 2>/dev/null | awk '$6 == 0 {print $2}' | xargs -I{} ipcrm -m {} 2>/dev/null || true",{stdio:"ignore",timeout:5000})}catch{}}function signalPgserveTree(child,signal){let pid=child.pid;if(pid===void 0){try{child.kill(signal)}catch{}return}try{if(process.platform==="win32")child.kill(signal);else process.kill(-pid,signal)}catch{try{child.kill(signal)}catch{}}}async function terminatePgserveTree(child){if(signalPgserveTree(child,"SIGTERM"),!await new Promise((resolve3)=>{if(child.exitCode!==null||child.signalCode!==null){resolve3(!0);return}let timer2=setTimeout(()=>resolve3(!1),1000);timer2.unref(),child.once("exit",()=>{clearTimeout(timer2),resolve3(!0)})}))signalPgserveTree(child,"SIGKILL")}function getPort(){let envPort=process.env.GENIE_PG_PORT;if(envPort){let parsed=Number.parseInt(envPort,10);if(!Number.isNaN(parsed)&&parsed>0&&parsed<65536)return parsed}return DEFAULT_PORT}async function isPostgresHealthy(port){try{return await Promise.race([(async()=>{let pg=(await Promise.resolve().then(() => (init_src(),exports_src))).default,probe=pg({host:DEFAULT_HOST,port,database:DB_NAME,username:"postgres",password:"postgres",max:1,connect_timeout:3,idle_timeout:1});try{return await probe`SELECT 1`,await probe.end({timeout:2}),!0}catch{try{await probe.end({timeout:1})}catch{}return!1}})(),new Promise((resolve3)=>{setTimeout(()=>resolve3(!1),4000).unref()})])}catch{return!1}}function readLockfile(){try{let content=readFileSync9(LOCKFILE_PATH,"utf-8").trim(),port=Number.parseInt(content,10);if(!Number.isNaN(port)&&port>0&&port<65536)return port}catch{}return null}function writeLockfile(port){try{mkdirSync6(GENIE_HOME,{recursive:!0});let tmpPath=`${LOCKFILE_PATH}.tmp.${process.pid}`;writeFileSync6(tmpPath,String(port),"utf-8"),renameSync(tmpPath,LOCKFILE_PATH)}catch{}}function removeLockfile(){try{unlinkSync3(LOCKFILE_PATH)}catch{}}async function runRetention(sql){try{await sql.unsafe(`
|
|
679
679
|
DELETE FROM heartbeats WHERE created_at < now() - interval '7 days';
|
|
680
680
|
DELETE FROM machine_snapshots WHERE created_at < now() - interval '30 days';
|
|
681
681
|
DELETE FROM audit_events WHERE entity_type LIKE 'otel_%' AND created_at < now() - interval '30 days';
|
|
682
682
|
DELETE FROM genie_runtime_events WHERE created_at < now() - interval '14 days';
|
|
683
683
|
`),retentionRan=!0}catch(retErr){retentionRan=!0;let msg=retErr instanceof Error?retErr.message:String(retErr);process.stderr.write(`[genie] retention cleanup warning: ${msg}
|
|
684
|
-
`)}}async function ensurePgserve(){if(activePort===null){let testPort=await resolveTestPort();if(testPort!==null)return activePort=testPort,process.env.GENIE_PG_AVAILABLE="true",testPort}if(ensurePromise)return ensurePromise;ensurePromise=_ensurePgserve();try{return await ensurePromise}finally{ensurePromise=null}}function __setSpawnDaemonForTest(fn){spawnDaemon=fn??(()=>{let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn(bunPath,[genieBin,"serve","start","--headless","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref()})}function readPidFile(pidPath){try{return readFileSync9(pidPath,"utf-8").trim()||null}catch{return null}}function parsePidFile(raw){let sepIdx=raw.indexOf(":"),pid,recordedStartTime;if(sepIdx<0)pid=Number.parseInt(raw,10),recordedStartTime=null;else{pid=Number.parseInt(raw.slice(0,sepIdx),10);let tail=raw.slice(sepIdx+1).trim();recordedStartTime=tail===""||tail==="unknown"?null:tail}if(Number.isNaN(pid)||pid<=0)return null;return{pid,recordedStartTime}}function isServeAlive(pid,recordedStartTime){try{process.kill(pid,0)}catch{return!1}if(recordedStartTime===null)return!1;let currentStartTime=getProcessStartTime(pid);return currentStartTime!==null&¤tStartTime===recordedStartTime}function unlinkQuiet(path2){try{unlinkSync3(path2)}catch{}}async function autoStartDaemon(){let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join17(home,"serve.pid"),raw=readPidFile(pidPath);if(!raw){lastAutoStartOutcome="missing",lastAutoStartPid=null,spawnDaemon();return}let parsed=parsePidFile(raw);if(!parsed){unlinkQuiet(pidPath),lastAutoStartOutcome="stale",lastAutoStartPid=null,spawnDaemon();return}if(isServeAlive(parsed.pid,parsed.recordedStartTime)){lastAutoStartOutcome="alive",lastAutoStartPid=parsed.pid;return}unlinkQuiet(pidPath),lastAutoStartOutcome="stale",lastAutoStartPid=parsed.pid,spawnDaemon()}async function resolveTestPort(){let raw=process.env.GENIE_TEST_PG_PORT;if(!raw)return null;let parsed=Number.parseInt(raw,10);if(Number.isNaN(parsed)||parsed<=0||parsed>=65536||!await isPostgresHealthy(parsed))throw Error(`GENIE_TEST_PG_PORT=${raw} set but not reachable`);return parsed}async function tryExistingPort(port){let portFromFile=readLockfile();if(portFromFile!==null&&await isPostgresHealthy(portFromFile))return activePort=portFromFile,process.env.GENIE_PG_AVAILABLE="true",portFromFile;if(await isPostgresHealthy(port))return activePort=port,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;return null}async function spawnPgserveDirect(port){mkdirSync6(DATA_DIR,{recursive:!0}),selfHealPostgres(DATA_DIR);try{let startedPort=await startPgserveOnPort(port);return registerExitHandler(),startedPort}catch(err){process.env.GENIE_PG_AVAILABLE="false";let message=err instanceof Error?err.message:String(err);throw Error(`pgserve failed to start: ${maskCredentials(message)}`)}}async function waitForDaemonPort(){let deadline=Date.now()+16000;while(Date.now()<deadline){let p=readLockfile();if(p!==null&&await isPostgresHealthy(p))return activePort=p,process.env.GENIE_PG_AVAILABLE="true",p;await new Promise((r)=>setTimeout(r,500))}return null}function throwDaemonTimeout(outcomeAtStart,pidAtStart){process.env.GENIE_PG_AVAILABLE="false";let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join17(home,"serve.pid"),hasPidFile=existsSync13(pidPath),currentPort=readLockfile()??getPort();if(outcomeAtStart==="stale")throw Error(`Stale ~/.genie/serve.pid (PID ${pidAtStart??"unknown"} was not our serve). Removed and retried \u2014 if this persists, run: genie serve start`);if(!hasPidFile)throw Error("genie serve not running. Run: genie serve start");throw Error(`genie serve is running (PID ${pidAtStart??outcomeAtStart??"unknown"}) but pgserve did not respond on port ${currentPort} within 16s. Try: genie serve restart, or check ~/.genie/logs/scheduler.log`)}async function _ensurePgserve(){if(activePort!==null)return activePort;let port=getPort(),existing=await tryExistingPort(port);if(existing!==null)return existing;if(process.env.CI==="true")throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve not available in CI");if(isPgAutostartDisabled())throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve unavailable and GENIE_PG_NO_AUTOSTART=1");let rootErr=checkRootGuard();if(rootErr!==null)throw process.env.GENIE_PG_AVAILABLE="false",Error(rootErr);if(process.env.GENIE_IS_DAEMON==="1")return spawnPgserveDirect(port);await autoStartDaemon();let outcomeAtStart=lastAutoStartOutcome,pidAtStart=lastAutoStartPid,waited=await waitForDaemonPort();if(waited!==null)return waited;throwDaemonTimeout(outcomeAtStart,pidAtStart)}function findPgserveBin(){try{let resolved=__require.resolve("pgserve/bin/pgserve-wrapper.cjs");if(existsSync13(resolved))return resolved}catch{}let globalBin=join17(homedir11(),".bun","bin","pgserve");if(existsSync13(globalBin))return globalBin;try{return execSync3("which pgserve",{encoding:"utf-8",timeout:3000}).trim()}catch{return"pgserve"}}async function startPgserveOnPort(port){mkdirSync6(DATA_DIR,{recursive:!0});let child=spawn(findPgserveBin(),["--port",String(port),"--host",DEFAULT_HOST,"--data",DATA_DIR,"--log","warn","--no-stats","--no-cluster","--pgvector"],{detached:!0,stdio:"ignore"});child.unref(),pgserveChild=child;let timeout=Number(process.env.GENIE_PGSERVE_TIMEOUT)||30000,deadline=Date.now()+timeout;while(Date.now()<deadline){if(await isPostgresHealthy(port))return activePort=port,ownsLockfile=!0,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;await new Promise((r)=>setTimeout(r,500))}try{child.kill("SIGTERM")}catch{}throw Error(`pgserve failed to start on port ${port} (timeout after ${timeout/1000}s)`)}function registerExitHandler(){if(exitHandlerRegistered)return;exitHandlerRegistered=!0;let cleanup=()=>{if(pgserveChild){try{pgserveChild.kill("SIGTERM")}catch{}pgserveChild=null}if(ownsLockfile)removeLockfile(),ownsLockfile=!1};process.on("exit",cleanup),process.on("SIGINT",()=>{cleanup(),process.exit(130)}),process.on("SIGTERM",()=>{cleanup(),process.exit(143)})}async function healthCheckCachedClient(){if(!sqlClient)return null;try{return await sqlClient`SELECT 1`,sqlClient}catch{let dying=sqlClient;if(!dying)return null;return sqlClient=null,activePort=null,dying.end({timeout:5}).catch(()=>{}),null}}async function runPostConnectSetup(client,isTestMode,timings){let _t2=Date.now(),skipBoot=isTestMode||process.env.GENIE_SKIP_DB_BOOT==="1";if(!skipBoot)await runMigrations(client);let _t3=Date.now();if(!skipBoot&&(needsSeed()||await needsSeededTeams(client)))await runSeed(client);let _t4=Date.now(),_t5=_t4;if(process.env.GENIE_PROFILE_DB)console.error(`[db-profile] pgserve=${timings.t1-timings.t0}ms migrate=${_t3-_t2}ms seed=${_t4-_t3}ms retention=skipped total=${_t5-timings.t0}ms`)}async function getConnection(){let cached=await healthCheckCachedClient();if(cached)return cached;if(buildPromise)return buildPromise;buildPromise=_buildConnection();try{return await buildPromise}finally{buildPromise=null}}async function _buildConnection(){let _t0=Date.now(),port=await ensurePgserve(),_t1=Date.now(),pgModule=(await Promise.resolve().then(() => (init_src(),exports_src))).default,testDbName=process.env.GENIE_TEST_DB_NAME,database=testDbName&&testDbName.length>0?testDbName:DB_NAME,isTestMode=Boolean(testDbName);sqlClient=pgModule({host:DEFAULT_HOST,port,database,username:"postgres",password:"postgres",max:50,idle_timeout:1,connect_timeout:5,onnotice:()=>{},connection:{client_min_messages:"warning"}});try{await runPostConnectSetup(sqlClient,isTestMode,{t0:_t0,t1:_t1})}catch(err){let dying=sqlClient;throw sqlClient=null,activePort=null,dying?.end({timeout:2}).catch(()=>{}),err}return sqlClient}function isConnected(){return sqlClient!==null}async function resetConnection(){if(sqlClient){let dying=sqlClient;sqlClient=null,await dying.end({timeout:5})}}async function isAvailable(){try{return await(await getConnection())`SELECT 1`,!0}catch{return!1}}async function shutdown(){if(sqlClient)await sqlClient.end({timeout:5}),sqlClient=null;if(ownsLockfile)removeLockfile(),ownsLockfile=!1}function getDataDir(){return DATA_DIR}function getActivePort(){return activePort??getPort()}function getLockfilePath(){return LOCKFILE_PATH}var DEFAULT_PORT=19642,DEFAULT_HOST="127.0.0.1",GENIE_HOME,DATA_DIR,LOCKFILE_PATH,DB_NAME="genie",TRUTHY_ENV,pgserveChild=null,sqlClient=null,activePort=null,ensurePromise=null,buildPromise=null,ownsLockfile=!1,exitHandlerRegistered=!1,retentionRan=!1,lastAutoStartOutcome=null,lastAutoStartPid=null,spawnDaemon=()=>{let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn(bunPath,[genieBin,"serve","start","--headless","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref()};var init_db=__esm(()=>{init_db_migrations();init_pg_seed();init_process_identity();GENIE_HOME=process.env.GENIE_HOME??join17(homedir11(),".genie"),DATA_DIR=join17(GENIE_HOME,"data","pgserve"),LOCKFILE_PATH=join17(GENIE_HOME,"pgserve.port"),TRUTHY_ENV=new Set(["1","true","yes","on"])});import{createHmac as createHmac2}from"crypto";import{homedir as homedir12}from"os";function hashEntity(namespace,value){let key=process.env.GENIE_REDACTION_KEY??"genie-redaction-fallback";return`tier-a:${namespace}:${createHmac2("sha256",key).update(value).digest("hex").slice(0,16)}`}function dropSecretShaped(text){let out=text;for(let{name,pattern}of SECRET_PATTERNS)out=out.replace(pattern,`<REDACTED:${name}>`);return out}function stripEnvVars(text){return text.replace(ENV_ASSIGN,(_m,name)=>`${name}=<REDACTED>`)}function tokenizePath(p){let home=homedir12(),out=p;if(home&&out.startsWith(home))out=`~${out.slice(home.length)}`;let segments=out.split("/").filter(Boolean);if(segments.length>6){let head=segments.slice(0,3).join("/"),tail=segments.slice(-2).join("/");out=`${out.startsWith("/")?"/":""}${head}/\u2026/${tail}`}return out=out.replace(/\b[0-9a-f]{12,}\b/g,"<id>"),out}function redactFreeText(value){return stripEnvVars(dropSecretShaped(value))}function capPayload(body){let serialized;try{serialized=JSON.stringify(body)}catch{return{overflow:!0,content_hash:"unserializable",body:{overflow:!0}}}if(Buffer.byteLength(serialized,"utf8")<=MAX_PAYLOAD_BYTES)return{overflow:!1,body};let key=process.env.GENIE_REDACTION_KEY??"genie-redaction-fallback",digest=createHmac2("sha256",key).update(serialized).digest("hex").slice(0,16);return{overflow:!0,content_hash:digest,body:{overflow:!0,content_hash:digest,original_bytes:Buffer.byteLength(serialized,"utf8")}}}var SECRET_PATTERNS,SENSITIVE_ENV_NAME="[A-Z][A-Z0-9_]*(?:_KEY|_SECRET|_TOKEN|_PASSWORD|_PASS|_AUTH|_API_KEY)",ENV_ASSIGN,MAX_PAYLOAD_BYTES=65536;var init_redactors=__esm(()=>{SECRET_PATTERNS=[{name:"anthropic-key",pattern:/sk-ant-[A-Za-z0-9_-]{20,}/g},{name:"openai-key",pattern:/sk-[A-Za-z0-9]{20,}/g},{name:"github-token",pattern:/gh[pousr]_[A-Za-z0-9]{30,}/g},{name:"aws-access-key",pattern:/AKIA[0-9A-Z]{16}/g},{name:"aws-secret",pattern:/(?<![A-Za-z0-9])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9])/g},{name:"bearer-token",pattern:/(?:Bearer|bearer)\s+[A-Za-z0-9._\-~+/=]{20,}/g},{name:"jwt",pattern:/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g},{name:"pem-header",pattern:/-----BEGIN [A-Z ]+ PRIVATE KEY-----/g},{name:"sensitive-path",pattern:/\/(?:[^\s"',;():]+\/)*\.(?:secrets|ssh|aws|gnupg|keys)(?:\/[^\s"',;():]*)?/g}];ENV_ASSIGN=new RegExp(`\\b(${SENSITIVE_ENV_NAME})\\s*[=:]\\s*([^\\s"',;]+)`,"g")});function tagTier(schema2,tier,note){let desc=`tier:${tier}${note?`; ${note}`:""}`;return schema2.describe(desc)}var exports_agent_lifecycle={};__export(exports_agent_lifecycle,{schema:()=>schema2,TYPE:()=>TYPE,SCHEMA_VERSION:()=>SCHEMA_VERSION,KIND:()=>KIND});var SCHEMA_VERSION=1,TYPE="agent.lifecycle",KIND="span",AgentIdSchema,TeamSchema,ExecutorSchema,SessionIdSchema,CwdSchema,ExitReasonSchema,DurationSchema,schema2;var init_agent_lifecycle=__esm(()=>{init_zod();init_redactors();AgentIdSchema=tagTier(exports_external.string().min(1).max(256),"B","agent name \u2014 public"),TeamSchema=tagTier(exports_external.string().min(1).max(256).optional(),"B"),ExecutorSchema=tagTier(exports_external.enum(["claude-code","claude-sdk","codex","shell"]),"C"),SessionIdSchema=tagTier(exports_external.string().min(1).max(128).transform((v)=>hashEntity("session",v)),"A","session id hashed"),CwdSchema=tagTier(exports_external.string().max(1024).transform(tokenizePath),"B"),ExitReasonSchema=tagTier(exports_external.enum(["stopped","killed","crashed","idle-suspend","completed"]),"C"),DurationSchema=tagTier(exports_external.number().int().min(0),"C","ms"),schema2=exports_external.object({agent_id:AgentIdSchema,team:TeamSchema,executor:ExecutorSchema,session_id:SessionIdSchema.optional(),cwd:CwdSchema.optional(),exit_reason:ExitReasonSchema.optional(),duration_ms:DurationSchema.optional()}).strict()});var exports_agent_resume_attempted={};__export(exports_agent_resume_attempted,{schema:()=>schema3,TYPE:()=>TYPE2,SCHEMA_VERSION:()=>SCHEMA_VERSION2,KIND:()=>KIND2});var SCHEMA_VERSION2=1,TYPE2="agent.resume.attempted",KIND2="event",AGENT_STATES,EntityIdSchema,AttemptNumberSchema,StateSchema,LastErrorSchema,TriggerSchema,schema3;var init_agent_resume_attempted=__esm(()=>{init_zod();init_redactors();AGENT_STATES=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema=tagTier(exports_external.enum(AGENT_STATES),"C"),LastErrorSchema=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),schema3=exports_external.object({entity_id:EntityIdSchema,attempt_number:AttemptNumberSchema,state_before:StateSchema,state_after:StateSchema,last_error:LastErrorSchema,trigger:TriggerSchema}).strict()});var exports_agent_resume_failed={};__export(exports_agent_resume_failed,{schema:()=>schema4,TYPE:()=>TYPE3,SCHEMA_VERSION:()=>SCHEMA_VERSION3,KIND:()=>KIND3});var SCHEMA_VERSION3=1,TYPE3="agent.resume.failed",KIND3="event",AGENT_STATES2,EntityIdSchema2,AttemptNumberSchema2,StateSchema2,LastErrorSchema2,TriggerSchema2,ExhaustedSchema,schema4;var init_agent_resume_failed=__esm(()=>{init_zod();init_redactors();AGENT_STATES2=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema2=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema2=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema2=tagTier(exports_external.enum(AGENT_STATES2),"C"),LastErrorSchema2=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema2=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),ExhaustedSchema=tagTier(exports_external.boolean(),"C"),schema4=exports_external.object({entity_id:EntityIdSchema2,attempt_number:AttemptNumberSchema2,state_before:StateSchema2,state_after:StateSchema2,last_error:LastErrorSchema2,trigger:TriggerSchema2,exhausted:ExhaustedSchema}).strict()});var exports_agent_resume_succeeded={};__export(exports_agent_resume_succeeded,{schema:()=>schema5,TYPE:()=>TYPE4,SCHEMA_VERSION:()=>SCHEMA_VERSION4,KIND:()=>KIND4});var SCHEMA_VERSION4=1,TYPE4="agent.resume.succeeded",KIND4="event",AGENT_STATES3,EntityIdSchema3,AttemptNumberSchema3,StateSchema3,LastErrorSchema3,TriggerSchema3,schema5;var init_agent_resume_succeeded=__esm(()=>{init_zod();init_redactors();AGENT_STATES3=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema3=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema3=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema3=tagTier(exports_external.enum(AGENT_STATES3),"C"),LastErrorSchema3=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema3=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),schema5=exports_external.object({entity_id:EntityIdSchema3,attempt_number:AttemptNumberSchema3,state_before:StateSchema3,state_after:StateSchema3,last_error:LastErrorSchema3,trigger:TriggerSchema3}).strict()});var exports_audit_export={};__export(exports_audit_export,{schema:()=>schema6,TYPE:()=>TYPE5,SCHEMA_VERSION:()=>SCHEMA_VERSION5,KIND:()=>KIND5,DEFAULT_TIER:()=>DEFAULT_TIER});var SCHEMA_VERSION5=1,TYPE5="audit.export",KIND5="event",DEFAULT_TIER="audit",ExporterActorSchema,SinceIdSchema,RowCountSchema,BreakCountSchema,BundleSignaturePrefixSchema,TenantIdSchema,ReasonSchema,schema6;var init_audit_export=__esm(()=>{init_zod();init_redactors();ExporterActorSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A"),SinceIdSchema=tagTier(exports_external.number().int().min(0),"C"),RowCountSchema=tagTier(exports_external.number().int().min(0),"C"),BreakCountSchema=tagTier(exports_external.number().int().min(0),"C","chain breaks detected in the exported range"),BundleSignaturePrefixSchema=tagTier(exports_external.string().min(1).max(16),"C","first 16 hex of the bundle HMAC signature (full is on disk)"),TenantIdSchema=tagTier(exports_external.string().min(1).max(128),"C"),ReasonSchema=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)),"B","IR justification for the export"),schema6=exports_external.object({exporter_actor:ExporterActorSchema,since_id:SinceIdSchema,row_count:RowCountSchema,break_count:BreakCountSchema,bundle_signature_prefix:BundleSignaturePrefixSchema,tenant_id:TenantIdSchema,reason:ReasonSchema}).strict()});var exports_audit_un_hash={};__export(exports_audit_un_hash,{schema:()=>schema7,TYPE:()=>TYPE6,SCHEMA_VERSION:()=>SCHEMA_VERSION6,KIND:()=>KIND6,DEFAULT_TIER:()=>DEFAULT_TIER2});var SCHEMA_VERSION6=1,TYPE6="audit.un_hash",KIND6="event",DEFAULT_TIER2="audit",AdminActorSchema,NamespaceSchema,HashedValueSchema,ResolvedMarkerSchema,ReasonSchema2,TicketRefSchema,schema7;var init_audit_un_hash=__esm(()=>{init_zod();init_redactors();AdminActorSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A","admin who performed the un-hash (Tier-A hashed)"),NamespaceSchema=tagTier(exports_external.string().min(1).max(64),"C"),HashedValueSchema=tagTier(exports_external.string().min(1).max(256),"B","tier-a:ns:... source hash requested"),ResolvedMarkerSchema=tagTier(exports_external.boolean(),"C","true if un-hash succeeded"),ReasonSchema2=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)),"B","IR justification for the un-hash"),TicketRefSchema=tagTier(exports_external.string().max(128).optional(),"C","incident ticket reference"),schema7=exports_external.object({admin_actor:AdminActorSchema,namespace:NamespaceSchema,hashed_value:HashedValueSchema,resolved:ResolvedMarkerSchema,reason:ReasonSchema2,ticket_ref:TicketRefSchema}).strict()});var exports_cache_hit={};__export(exports_cache_hit,{schema:()=>schema8,TYPE:()=>TYPE7,SCHEMA_VERSION:()=>SCHEMA_VERSION7,KIND:()=>KIND7});var SCHEMA_VERSION7=1,TYPE7="cache.hit",KIND7="event",CacheSchema,HitSchema,KeyHintSchema,LatencyUsSchema,schema8;var init_cache_hit=__esm(()=>{init_zod();init_redactors();CacheSchema=tagTier(exports_external.string().min(1).max(128),"C"),HitSchema=tagTier(exports_external.boolean(),"C"),KeyHintSchema=tagTier(exports_external.string().max(128).transform((v)=>redactFreeText(v)).optional(),"B"),LatencyUsSchema=tagTier(exports_external.number().int().min(0).max(1e7).optional(),"C","microseconds"),schema8=exports_external.object({cache:CacheSchema,hit:HitSchema,key_hint:KeyHintSchema,latency_us:LatencyUsSchema}).strict()});var exports_cache_invalidate={};__export(exports_cache_invalidate,{schema:()=>schema9,TYPE:()=>TYPE8,SCHEMA_VERSION:()=>SCHEMA_VERSION8,KIND:()=>KIND8});var SCHEMA_VERSION8=1,TYPE8="cache.invalidate",KIND8="event",CacheSchema2,KeysInvalidatedSchema,ReasonSchema3,ScopeSchema,schema9;var init_cache_invalidate=__esm(()=>{init_zod();CacheSchema2=tagTier(exports_external.string().min(1).max(128),"C","cache name \u2014 public"),KeysInvalidatedSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),ReasonSchema3=tagTier(exports_external.enum(["ttl","manual","capacity","rotation","upstream_change"]).optional(),"C"),ScopeSchema=tagTier(exports_external.enum(["key","bucket","all"]).optional(),"C"),schema9=exports_external.object({cache:CacheSchema2,keys_invalidated:KeysInvalidatedSchema,reason:ReasonSchema3,scope:ScopeSchema}).strict()});var exports_cli_command={};__export(exports_cli_command,{schema:()=>schema10,TYPE:()=>TYPE9,SCHEMA_VERSION:()=>SCHEMA_VERSION9,KIND:()=>KIND9});var SCHEMA_VERSION9=1,TYPE9="cli.command",KIND9="span",CommandSchema,ArgsSchema,CwdSchema2,ExitCodeSchema,DurationSchema2,UserAgentSchema,schema10;var init_cli_command=__esm(()=>{init_zod();init_redactors();CommandSchema=tagTier(exports_external.string().max(256),"C","subcommand name only"),ArgsSchema=tagTier(exports_external.array(exports_external.string()).max(32).transform((args)=>args.map((a)=>redactFreeText(a))),"B","argv \u2014 secrets stripped, paths kept"),CwdSchema2=tagTier(exports_external.string().max(1024).transform(tokenizePath),"B","working directory tokenized"),ExitCodeSchema=tagTier(exports_external.number().int().min(-1).max(255),"C"),DurationSchema2=tagTier(exports_external.number().int().min(0).max(3600000),"C","milliseconds"),UserAgentSchema=tagTier(exports_external.string().max(256).optional(),"C"),schema10=exports_external.object({command:CommandSchema,args:ArgsSchema,cwd:CwdSchema2,exit_code:ExitCodeSchema.optional(),duration_ms:DurationSchema2.optional(),user_agent:UserAgentSchema}).strict().transform((v)=>({...v}))});var exports_consumer_heartbeat={};__export(exports_consumer_heartbeat,{schema:()=>schema11,TYPE:()=>TYPE10,SCHEMA_VERSION:()=>SCHEMA_VERSION10,KIND:()=>KIND10});var SCHEMA_VERSION10=1,TYPE10="consumer.heartbeat",KIND10="event",ConsumerIdSchema,LastEventIdSchema,BacklogDepthSchema,RoleSchema,UptimeSecondsSchema,schema11;var init_consumer_heartbeat=__esm(()=>{init_zod();init_redactors();ConsumerIdSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("consumer",v)),"A"),LastEventIdSchema=tagTier(exports_external.number().int().min(0).max(9007199254740991),"C"),BacklogDepthSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),RoleSchema=tagTier(exports_external.enum(["admin","operator","subscriber","audit"]).optional(),"C"),UptimeSecondsSchema=tagTier(exports_external.number().int().min(0).max(31536000).optional(),"C"),schema11=exports_external.object({consumer_id:ConsumerIdSchema,last_event_id_processed:LastEventIdSchema,backlog_depth:BacklogDepthSchema,role:RoleSchema,uptime_seconds:UptimeSecondsSchema}).strict()});var exports_consumer_lagged={};__export(exports_consumer_lagged,{schema:()=>schema12,TYPE:()=>TYPE11,SCHEMA_VERSION:()=>SCHEMA_VERSION11,KIND:()=>KIND11,DEFAULT_TIER:()=>DEFAULT_TIER3});var SCHEMA_VERSION11=1,TYPE11="consumer.lagged",KIND11="event",DEFAULT_TIER3="audit",CountSchema,SpillPathSchema,SeveritySchema,schema12;var init_consumer_lagged=__esm(()=>{init_zod();CountSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),SpillPathSchema=tagTier(exports_external.string().max(512),"B"),SeveritySchema=tagTier(exports_external.enum(["warn","error","fatal"]),"C"),schema12=exports_external.object({severity_class:SeveritySchema,spill_path:SpillPathSchema,rows_spilled:CountSchema,queue_depth:CountSchema,queue_cap:CountSchema}).strict()});var exports_correlation_orphan_rate={};__export(exports_correlation_orphan_rate,{schema:()=>schema13,TYPE:()=>TYPE12,SCHEMA_VERSION:()=>SCHEMA_VERSION12,KIND:()=>KIND12});var SCHEMA_VERSION12=1,TYPE12="correlation.orphan.rate",KIND12="event",RateSchema,CountSchema2,schema13;var init_correlation_orphan_rate=__esm(()=>{init_zod();RateSchema=tagTier(exports_external.number().min(0).max(1),"C"),CountSchema2=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema13=exports_external.object({window_samples:CountSchema2,orphans:CountSchema2,rate:RateSchema}).strict()});var exports_detector_disabled={};__export(exports_detector_disabled,{schema:()=>schema14,TYPE:()=>TYPE13,SCHEMA_VERSION:()=>SCHEMA_VERSION13,KIND:()=>KIND13});var SCHEMA_VERSION13=1,TYPE13="detector.disabled",KIND13="event",DetectorIdSchema,CauseSchema,BudgetSchema,FireCountSchema,BucketEndTsSchema,schema14;var init_detector_disabled=__esm(()=>{init_zod();DetectorIdSchema=tagTier(exports_external.string().min(1).max(128),"C"),CauseSchema=tagTier(exports_external.literal("fire_budget_exceeded"),"C"),BudgetSchema=tagTier(exports_external.number().int().min(1).max(1e6),"C","events per hour bucket"),FireCountSchema=tagTier(exports_external.number().int().min(0).max(1e6),"C","fires observed in this bucket"),BucketEndTsSchema=tagTier(exports_external.string().datetime({offset:!0}),"C","ISO-8601 timestamp when the current hour bucket expires"),schema14=exports_external.object({detector_id:DetectorIdSchema,cause:CauseSchema,budget:BudgetSchema,fire_count:FireCountSchema,bucket_end_ts:BucketEndTsSchema}).strict()});var exports_emit_backpressure_critical={};__export(exports_emit_backpressure_critical,{schema:()=>schema15,TYPE:()=>TYPE14,SCHEMA_VERSION:()=>SCHEMA_VERSION14,KIND:()=>KIND14,DEFAULT_TIER:()=>DEFAULT_TIER4});var SCHEMA_VERSION14=1,TYPE14="emit.backpressure.critical",KIND14="event",DEFAULT_TIER4="audit",SecondsSchema,CountSchema3,schema15;var init_emit_backpressure_critical=__esm(()=>{init_zod();SecondsSchema=tagTier(exports_external.number().min(0).max(86400),"C"),CountSchema3=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema15=exports_external.object({spill_duration_seconds:SecondsSchema,spill_rows_total:CountSchema3,queue_depth:CountSchema3,queue_cap:CountSchema3,recommended_action:tagTier(exports_external.enum(["scale_consumers","inspect_pg","restart_bridge"]).optional(),"C")}).strict()});var exports_emitter_latency_p99={};__export(exports_emitter_latency_p99,{schema:()=>schema16,TYPE:()=>TYPE15,SCHEMA_VERSION:()=>SCHEMA_VERSION15,KIND:()=>KIND15});var SCHEMA_VERSION15=1,TYPE15="emitter.latency_p99",KIND15="event",MillisSchema,SampleCountSchema,schema16;var init_emitter_latency_p99=__esm(()=>{init_zod();MillisSchema=tagTier(exports_external.number().min(0).max(600000),"C"),SampleCountSchema=tagTier(exports_external.number().int().min(1).max(1e6),"C"),schema16=exports_external.object({window_samples:SampleCountSchema,p50_ms:MillisSchema,p95_ms:MillisSchema,p99_ms:MillisSchema,max_ms:MillisSchema}).strict()});var exports_emitter_queue_depth={};__export(exports_emitter_queue_depth,{schema:()=>schema17,TYPE:()=>TYPE16,SCHEMA_VERSION:()=>SCHEMA_VERSION16,KIND:()=>KIND16});var SCHEMA_VERSION16=1,TYPE16="emitter.queue.depth",KIND16="event",DepthSchema,CapSchema,UtilizationSchema,schema17;var init_emitter_queue_depth=__esm(()=>{init_zod();DepthSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),CapSchema=tagTier(exports_external.number().int().min(1).max(1e7),"C"),UtilizationSchema=tagTier(exports_external.number().min(0).max(1),"C"),schema17=exports_external.object({depth:DepthSchema,cap:CapSchema,utilization:UtilizationSchema,enqueued_total:tagTier(exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER),"C"),flushed_total:tagTier(exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER),"C")}).strict()});var exports_emitter_rejected={};__export(exports_emitter_rejected,{schema:()=>schema18,TYPE:()=>TYPE17,SCHEMA_VERSION:()=>SCHEMA_VERSION17,KIND:()=>KIND17});var SCHEMA_VERSION17=1,TYPE17="emitter.rejected",KIND17="event",OffendingTypeSchema,ReasonSchema4,CountSchema4,schema18;var init_emitter_rejected=__esm(()=>{init_zod();OffendingTypeSchema=tagTier(exports_external.string().min(1).max(128),"C"),ReasonSchema4=tagTier(exports_external.enum(["schema_parse","unregistered","kind_mismatch","overflow_cap","queue_full"]),"C"),CountSchema4=tagTier(exports_external.number().int().min(1).max(1e7),"C"),schema18=exports_external.object({offending_type:OffendingTypeSchema,reason:ReasonSchema4,count:CountSchema4}).strict()});var exports_emitter_shedding_load={};__export(exports_emitter_shedding_load,{schema:()=>schema19,TYPE:()=>TYPE18,SCHEMA_VERSION:()=>SCHEMA_VERSION18,KIND:()=>KIND18});var SCHEMA_VERSION18=1,TYPE18="emitter.shedding_load",KIND18="event",CountSchema5,schema19;var init_emitter_shedding_load=__esm(()=>{init_zod();CountSchema5=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema19=exports_external.object({dropped_debug:CountSchema5,dropped_info:CountSchema5,spilled_warn_plus:CountSchema5,window_seconds:tagTier(exports_external.number().int().min(1).max(3600),"C")}).strict()});var exports_error_raised={};__export(exports_error_raised,{schema:()=>schema20,TYPE:()=>TYPE19,SCHEMA_VERSION:()=>SCHEMA_VERSION19,KIND:()=>KIND19});var SCHEMA_VERSION19=1,TYPE19="error.raised",KIND19="event",ErrorClassSchema,MessageSchema,StackSchema,SubsystemSchema,SeveritySchema2,RetryableSchema,schema20;var init_error_raised=__esm(()=>{init_zod();init_redactors();ErrorClassSchema=tagTier(exports_external.string().min(1).max(256),"C","exception class name"),MessageSchema=tagTier(exports_external.string().max(4096).transform(redactFreeText),"B"),StackSchema=tagTier(exports_external.string().max(16384).transform((stack)=>stack.split(`
|
|
684
|
+
`)}}async function ensurePgserve(){if(activePort===null){let testPort=await resolveTestPort();if(testPort!==null)return activePort=testPort,process.env.GENIE_PG_AVAILABLE="true",testPort}if(ensurePromise)return ensurePromise;ensurePromise=_ensurePgserve();try{return await ensurePromise}finally{ensurePromise=null}}function __setSpawnDaemonForTest(fn){spawnDaemon=fn??(()=>{let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn(bunPath,[genieBin,"serve","start","--headless","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref()})}function readPidFile(pidPath){try{return readFileSync9(pidPath,"utf-8").trim()||null}catch{return null}}function parsePidFile(raw){let sepIdx=raw.indexOf(":"),pid,recordedStartTime;if(sepIdx<0)pid=Number.parseInt(raw,10),recordedStartTime=null;else{pid=Number.parseInt(raw.slice(0,sepIdx),10);let tail=raw.slice(sepIdx+1).trim();recordedStartTime=tail===""||tail==="unknown"?null:tail}if(Number.isNaN(pid)||pid<=0)return null;return{pid,recordedStartTime}}function isServeAlive(pid,recordedStartTime){try{process.kill(pid,0)}catch{return!1}if(recordedStartTime===null)return!1;let currentStartTime=getProcessStartTime(pid);return currentStartTime!==null&¤tStartTime===recordedStartTime}function unlinkQuiet(path2){try{unlinkSync3(path2)}catch{}}async function autoStartDaemon(){let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join17(home,"serve.pid"),raw=readPidFile(pidPath);if(!raw){lastAutoStartOutcome="missing",lastAutoStartPid=null,spawnDaemon();return}let parsed=parsePidFile(raw);if(!parsed){unlinkQuiet(pidPath),lastAutoStartOutcome="stale",lastAutoStartPid=null,spawnDaemon();return}if(isServeAlive(parsed.pid,parsed.recordedStartTime)){lastAutoStartOutcome="alive",lastAutoStartPid=parsed.pid;return}unlinkQuiet(pidPath),lastAutoStartOutcome="stale",lastAutoStartPid=parsed.pid,spawnDaemon()}async function resolveTestPort(){let raw=process.env.GENIE_TEST_PG_PORT;if(!raw)return null;let parsed=Number.parseInt(raw,10);if(Number.isNaN(parsed)||parsed<=0||parsed>=65536||!await isPostgresHealthy(parsed))throw Error(`GENIE_TEST_PG_PORT=${raw} set but not reachable`);return parsed}async function tryExistingPort(port){let portFromFile=readLockfile();if(portFromFile!==null&&await isPostgresHealthy(portFromFile))return activePort=portFromFile,process.env.GENIE_PG_AVAILABLE="true",portFromFile;if(await isPostgresHealthy(port))return activePort=port,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;return null}async function spawnPgserveDirect(port){mkdirSync6(DATA_DIR,{recursive:!0}),selfHealPostgres(DATA_DIR);try{let startedPort=await startPgserveOnPort(port);return registerExitHandler(),startedPort}catch(err){process.env.GENIE_PG_AVAILABLE="false";let message=err instanceof Error?err.message:String(err);throw Error(`pgserve failed to start: ${maskCredentials(message)}`)}}async function waitForDaemonPort(){let deadline=Date.now()+16000;while(Date.now()<deadline){let p=readLockfile();if(p!==null&&await isPostgresHealthy(p))return activePort=p,process.env.GENIE_PG_AVAILABLE="true",p;await new Promise((r)=>setTimeout(r,500))}return null}function throwDaemonTimeout(outcomeAtStart,pidAtStart){process.env.GENIE_PG_AVAILABLE="false";let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join17(home,"serve.pid"),hasPidFile=existsSync13(pidPath),currentPort=readLockfile()??getPort();if(outcomeAtStart==="stale")throw Error(`Stale ~/.genie/serve.pid (PID ${pidAtStart??"unknown"} was not our serve). Removed and retried \u2014 if this persists, run: genie serve start`);if(!hasPidFile)throw Error("genie serve not running. Run: genie serve start");throw Error(`genie serve is running (PID ${pidAtStart??outcomeAtStart??"unknown"}) but pgserve did not respond on port ${currentPort} within 16s. Try: genie serve restart, or check ~/.genie/logs/scheduler.log`)}async function _ensurePgserve(){if(activePort!==null)return activePort;let port=getPort(),existing=await tryExistingPort(port);if(existing!==null)return existing;if(process.env.CI==="true")throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve not available in CI");if(isPgAutostartDisabled())throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve unavailable and GENIE_PG_NO_AUTOSTART=1");let rootErr=checkRootGuard();if(rootErr!==null)throw process.env.GENIE_PG_AVAILABLE="false",Error(rootErr);if(process.env.GENIE_IS_DAEMON==="1")return spawnPgserveDirect(port);await autoStartDaemon();let outcomeAtStart=lastAutoStartOutcome,pidAtStart=lastAutoStartPid,waited=await waitForDaemonPort();if(waited!==null)return waited;throwDaemonTimeout(outcomeAtStart,pidAtStart)}function findPgserveBin(){try{let resolved=__require.resolve("pgserve/bin/pgserve-wrapper.cjs");if(existsSync13(resolved))return resolved}catch{}let globalBin=join17(homedir11(),".bun","bin","pgserve");if(existsSync13(globalBin))return globalBin;try{return execSync3("which pgserve",{encoding:"utf-8",timeout:3000}).trim()}catch{return"pgserve"}}async function startPgserveOnPort(port){mkdirSync6(DATA_DIR,{recursive:!0});let child=spawn(findPgserveBin(),["--port",String(port),"--host",DEFAULT_HOST,"--data",DATA_DIR,"--log","warn","--no-stats","--no-cluster","--pgvector"],{detached:!0,stdio:"ignore"});child.unref(),pgserveChild=child;let timeout=Number(process.env.GENIE_PGSERVE_TIMEOUT)||30000,deadline=Date.now()+timeout;while(Date.now()<deadline){if(await isPostgresHealthy(port))return activePort=port,ownsLockfile=!0,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;await new Promise((r)=>setTimeout(r,500))}if(await terminatePgserveTree(child),pgserveChild===child)pgserveChild=null;throw selfHealPostgres(DATA_DIR),Error(`pgserve failed to start on port ${port} (timeout after ${timeout/1000}s)`)}function registerExitHandler(){if(exitHandlerRegistered)return;exitHandlerRegistered=!0;let cleanup=()=>{if(pgserveChild)signalPgserveTree(pgserveChild,"SIGTERM"),pgserveChild=null;if(ownsLockfile)removeLockfile(),ownsLockfile=!1};process.on("exit",cleanup),process.on("SIGINT",()=>{cleanup(),process.exit(130)}),process.on("SIGTERM",()=>{cleanup(),process.exit(143)})}async function healthCheckCachedClient(){if(!sqlClient)return null;try{return await sqlClient`SELECT 1`,sqlClient}catch{let dying=sqlClient;if(!dying)return null;return sqlClient=null,activePort=null,dying.end({timeout:5}).catch(()=>{}),null}}async function runPostConnectSetup(client,isTestMode,timings){let _t2=Date.now(),skipBoot=isTestMode||process.env.GENIE_SKIP_DB_BOOT==="1";if(!skipBoot)await runMigrations(client);let _t3=Date.now();if(!skipBoot&&(needsSeed()||await needsSeededTeams(client)))await runSeed(client);let _t4=Date.now(),_t5=_t4;if(process.env.GENIE_PROFILE_DB)console.error(`[db-profile] pgserve=${timings.t1-timings.t0}ms migrate=${_t3-_t2}ms seed=${_t4-_t3}ms retention=skipped total=${_t5-timings.t0}ms`)}async function getConnection(){let cached=await healthCheckCachedClient();if(cached)return cached;if(buildPromise)return buildPromise;buildPromise=_buildConnection();try{return await buildPromise}finally{buildPromise=null}}async function _buildConnection(){let _t0=Date.now(),port=await ensurePgserve(),_t1=Date.now(),pgModule=(await Promise.resolve().then(() => (init_src(),exports_src))).default,testDbName=process.env.GENIE_TEST_DB_NAME,database=testDbName&&testDbName.length>0?testDbName:DB_NAME,isTestMode=Boolean(testDbName);sqlClient=pgModule({host:DEFAULT_HOST,port,database,username:"postgres",password:"postgres",max:50,idle_timeout:1,connect_timeout:5,onnotice:()=>{},connection:{client_min_messages:"warning"}});try{await runPostConnectSetup(sqlClient,isTestMode,{t0:_t0,t1:_t1})}catch(err){let dying=sqlClient;throw sqlClient=null,activePort=null,dying?.end({timeout:2}).catch(()=>{}),err}return sqlClient}function isConnected(){return sqlClient!==null}async function resetConnection(){if(sqlClient){let dying=sqlClient;sqlClient=null,await dying.end({timeout:5})}}async function isAvailable(){try{return await(await getConnection())`SELECT 1`,!0}catch{return!1}}async function shutdown(){if(sqlClient)await sqlClient.end({timeout:5}),sqlClient=null;if(ownsLockfile)removeLockfile(),ownsLockfile=!1}function getDataDir(){return DATA_DIR}function getActivePort(){return activePort??getPort()}function getLockfilePath(){return LOCKFILE_PATH}var DEFAULT_PORT=19642,DEFAULT_HOST="127.0.0.1",GENIE_HOME,DATA_DIR,LOCKFILE_PATH,DB_NAME="genie",TRUTHY_ENV,pgserveChild=null,sqlClient=null,activePort=null,ensurePromise=null,buildPromise=null,ownsLockfile=!1,exitHandlerRegistered=!1,retentionRan=!1,lastAutoStartOutcome=null,lastAutoStartPid=null,spawnDaemon=()=>{let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn(bunPath,[genieBin,"serve","start","--headless","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref()};var init_db=__esm(()=>{init_db_migrations();init_pg_seed();init_process_identity();GENIE_HOME=process.env.GENIE_HOME??join17(homedir11(),".genie"),DATA_DIR=join17(GENIE_HOME,"data","pgserve"),LOCKFILE_PATH=join17(GENIE_HOME,"pgserve.port"),TRUTHY_ENV=new Set(["1","true","yes","on"])});import{createHmac as createHmac2}from"crypto";import{homedir as homedir12}from"os";function hashEntity(namespace,value){let key=process.env.GENIE_REDACTION_KEY??"genie-redaction-fallback";return`tier-a:${namespace}:${createHmac2("sha256",key).update(value).digest("hex").slice(0,16)}`}function dropSecretShaped(text){let out=text;for(let{name,pattern}of SECRET_PATTERNS)out=out.replace(pattern,`<REDACTED:${name}>`);return out}function stripEnvVars(text){return text.replace(ENV_ASSIGN,(_m,name)=>`${name}=<REDACTED>`)}function tokenizePath(p){let home=homedir12(),out=p;if(home&&out.startsWith(home))out=`~${out.slice(home.length)}`;let segments=out.split("/").filter(Boolean);if(segments.length>6){let head=segments.slice(0,3).join("/"),tail=segments.slice(-2).join("/");out=`${out.startsWith("/")?"/":""}${head}/\u2026/${tail}`}return out=out.replace(/\b[0-9a-f]{12,}\b/g,"<id>"),out}function redactFreeText(value){return stripEnvVars(dropSecretShaped(value))}function capPayload(body){let serialized;try{serialized=JSON.stringify(body)}catch{return{overflow:!0,content_hash:"unserializable",body:{overflow:!0}}}if(Buffer.byteLength(serialized,"utf8")<=MAX_PAYLOAD_BYTES)return{overflow:!1,body};let key=process.env.GENIE_REDACTION_KEY??"genie-redaction-fallback",digest=createHmac2("sha256",key).update(serialized).digest("hex").slice(0,16);return{overflow:!0,content_hash:digest,body:{overflow:!0,content_hash:digest,original_bytes:Buffer.byteLength(serialized,"utf8")}}}var SECRET_PATTERNS,SENSITIVE_ENV_NAME="[A-Z][A-Z0-9_]*(?:_KEY|_SECRET|_TOKEN|_PASSWORD|_PASS|_AUTH|_API_KEY)",ENV_ASSIGN,MAX_PAYLOAD_BYTES=65536;var init_redactors=__esm(()=>{SECRET_PATTERNS=[{name:"anthropic-key",pattern:/sk-ant-[A-Za-z0-9_-]{20,}/g},{name:"openai-key",pattern:/sk-[A-Za-z0-9]{20,}/g},{name:"github-token",pattern:/gh[pousr]_[A-Za-z0-9]{30,}/g},{name:"aws-access-key",pattern:/AKIA[0-9A-Z]{16}/g},{name:"aws-secret",pattern:/(?<![A-Za-z0-9])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9])/g},{name:"bearer-token",pattern:/(?:Bearer|bearer)\s+[A-Za-z0-9._\-~+/=]{20,}/g},{name:"jwt",pattern:/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g},{name:"pem-header",pattern:/-----BEGIN [A-Z ]+ PRIVATE KEY-----/g},{name:"sensitive-path",pattern:/\/(?:[^\s"',;():]+\/)*\.(?:secrets|ssh|aws|gnupg|keys)(?:\/[^\s"',;():]*)?/g}];ENV_ASSIGN=new RegExp(`\\b(${SENSITIVE_ENV_NAME})\\s*[=:]\\s*([^\\s"',;]+)`,"g")});function tagTier(schema2,tier,note){let desc=`tier:${tier}${note?`; ${note}`:""}`;return schema2.describe(desc)}var exports_agent_lifecycle={};__export(exports_agent_lifecycle,{schema:()=>schema2,TYPE:()=>TYPE,SCHEMA_VERSION:()=>SCHEMA_VERSION,KIND:()=>KIND});var SCHEMA_VERSION=1,TYPE="agent.lifecycle",KIND="span",AgentIdSchema,TeamSchema,ExecutorSchema,SessionIdSchema,CwdSchema,ExitReasonSchema,DurationSchema,schema2;var init_agent_lifecycle=__esm(()=>{init_zod();init_redactors();AgentIdSchema=tagTier(exports_external.string().min(1).max(256),"B","agent name \u2014 public"),TeamSchema=tagTier(exports_external.string().min(1).max(256).optional(),"B"),ExecutorSchema=tagTier(exports_external.enum(["claude-code","claude-sdk","codex","shell"]),"C"),SessionIdSchema=tagTier(exports_external.string().min(1).max(128).transform((v)=>hashEntity("session",v)),"A","session id hashed"),CwdSchema=tagTier(exports_external.string().max(1024).transform(tokenizePath),"B"),ExitReasonSchema=tagTier(exports_external.enum(["stopped","killed","crashed","idle-suspend","completed"]),"C"),DurationSchema=tagTier(exports_external.number().int().min(0),"C","ms"),schema2=exports_external.object({agent_id:AgentIdSchema,team:TeamSchema,executor:ExecutorSchema,session_id:SessionIdSchema.optional(),cwd:CwdSchema.optional(),exit_reason:ExitReasonSchema.optional(),duration_ms:DurationSchema.optional()}).strict()});var exports_agent_resume_attempted={};__export(exports_agent_resume_attempted,{schema:()=>schema3,TYPE:()=>TYPE2,SCHEMA_VERSION:()=>SCHEMA_VERSION2,KIND:()=>KIND2});var SCHEMA_VERSION2=1,TYPE2="agent.resume.attempted",KIND2="event",AGENT_STATES,EntityIdSchema,AttemptNumberSchema,StateSchema,LastErrorSchema,TriggerSchema,schema3;var init_agent_resume_attempted=__esm(()=>{init_zod();init_redactors();AGENT_STATES=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema=tagTier(exports_external.enum(AGENT_STATES),"C"),LastErrorSchema=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),schema3=exports_external.object({entity_id:EntityIdSchema,attempt_number:AttemptNumberSchema,state_before:StateSchema,state_after:StateSchema,last_error:LastErrorSchema,trigger:TriggerSchema}).strict()});var exports_agent_resume_failed={};__export(exports_agent_resume_failed,{schema:()=>schema4,TYPE:()=>TYPE3,SCHEMA_VERSION:()=>SCHEMA_VERSION3,KIND:()=>KIND3});var SCHEMA_VERSION3=1,TYPE3="agent.resume.failed",KIND3="event",AGENT_STATES2,EntityIdSchema2,AttemptNumberSchema2,StateSchema2,LastErrorSchema2,TriggerSchema2,ExhaustedSchema,schema4;var init_agent_resume_failed=__esm(()=>{init_zod();init_redactors();AGENT_STATES2=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema2=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema2=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema2=tagTier(exports_external.enum(AGENT_STATES2),"C"),LastErrorSchema2=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema2=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),ExhaustedSchema=tagTier(exports_external.boolean(),"C"),schema4=exports_external.object({entity_id:EntityIdSchema2,attempt_number:AttemptNumberSchema2,state_before:StateSchema2,state_after:StateSchema2,last_error:LastErrorSchema2,trigger:TriggerSchema2,exhausted:ExhaustedSchema}).strict()});var exports_agent_resume_succeeded={};__export(exports_agent_resume_succeeded,{schema:()=>schema5,TYPE:()=>TYPE4,SCHEMA_VERSION:()=>SCHEMA_VERSION4,KIND:()=>KIND4});var SCHEMA_VERSION4=1,TYPE4="agent.resume.succeeded",KIND4="event",AGENT_STATES3,EntityIdSchema3,AttemptNumberSchema3,StateSchema3,LastErrorSchema3,TriggerSchema3,schema5;var init_agent_resume_succeeded=__esm(()=>{init_zod();init_redactors();AGENT_STATES3=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema3=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema3=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema3=tagTier(exports_external.enum(AGENT_STATES3),"C"),LastErrorSchema3=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema3=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),schema5=exports_external.object({entity_id:EntityIdSchema3,attempt_number:AttemptNumberSchema3,state_before:StateSchema3,state_after:StateSchema3,last_error:LastErrorSchema3,trigger:TriggerSchema3}).strict()});var exports_audit_export={};__export(exports_audit_export,{schema:()=>schema6,TYPE:()=>TYPE5,SCHEMA_VERSION:()=>SCHEMA_VERSION5,KIND:()=>KIND5,DEFAULT_TIER:()=>DEFAULT_TIER});var SCHEMA_VERSION5=1,TYPE5="audit.export",KIND5="event",DEFAULT_TIER="audit",ExporterActorSchema,SinceIdSchema,RowCountSchema,BreakCountSchema,BundleSignaturePrefixSchema,TenantIdSchema,ReasonSchema,schema6;var init_audit_export=__esm(()=>{init_zod();init_redactors();ExporterActorSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A"),SinceIdSchema=tagTier(exports_external.number().int().min(0),"C"),RowCountSchema=tagTier(exports_external.number().int().min(0),"C"),BreakCountSchema=tagTier(exports_external.number().int().min(0),"C","chain breaks detected in the exported range"),BundleSignaturePrefixSchema=tagTier(exports_external.string().min(1).max(16),"C","first 16 hex of the bundle HMAC signature (full is on disk)"),TenantIdSchema=tagTier(exports_external.string().min(1).max(128),"C"),ReasonSchema=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)),"B","IR justification for the export"),schema6=exports_external.object({exporter_actor:ExporterActorSchema,since_id:SinceIdSchema,row_count:RowCountSchema,break_count:BreakCountSchema,bundle_signature_prefix:BundleSignaturePrefixSchema,tenant_id:TenantIdSchema,reason:ReasonSchema}).strict()});var exports_audit_un_hash={};__export(exports_audit_un_hash,{schema:()=>schema7,TYPE:()=>TYPE6,SCHEMA_VERSION:()=>SCHEMA_VERSION6,KIND:()=>KIND6,DEFAULT_TIER:()=>DEFAULT_TIER2});var SCHEMA_VERSION6=1,TYPE6="audit.un_hash",KIND6="event",DEFAULT_TIER2="audit",AdminActorSchema,NamespaceSchema,HashedValueSchema,ResolvedMarkerSchema,ReasonSchema2,TicketRefSchema,schema7;var init_audit_un_hash=__esm(()=>{init_zod();init_redactors();AdminActorSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A","admin who performed the un-hash (Tier-A hashed)"),NamespaceSchema=tagTier(exports_external.string().min(1).max(64),"C"),HashedValueSchema=tagTier(exports_external.string().min(1).max(256),"B","tier-a:ns:... source hash requested"),ResolvedMarkerSchema=tagTier(exports_external.boolean(),"C","true if un-hash succeeded"),ReasonSchema2=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)),"B","IR justification for the un-hash"),TicketRefSchema=tagTier(exports_external.string().max(128).optional(),"C","incident ticket reference"),schema7=exports_external.object({admin_actor:AdminActorSchema,namespace:NamespaceSchema,hashed_value:HashedValueSchema,resolved:ResolvedMarkerSchema,reason:ReasonSchema2,ticket_ref:TicketRefSchema}).strict()});var exports_cache_hit={};__export(exports_cache_hit,{schema:()=>schema8,TYPE:()=>TYPE7,SCHEMA_VERSION:()=>SCHEMA_VERSION7,KIND:()=>KIND7});var SCHEMA_VERSION7=1,TYPE7="cache.hit",KIND7="event",CacheSchema,HitSchema,KeyHintSchema,LatencyUsSchema,schema8;var init_cache_hit=__esm(()=>{init_zod();init_redactors();CacheSchema=tagTier(exports_external.string().min(1).max(128),"C"),HitSchema=tagTier(exports_external.boolean(),"C"),KeyHintSchema=tagTier(exports_external.string().max(128).transform((v)=>redactFreeText(v)).optional(),"B"),LatencyUsSchema=tagTier(exports_external.number().int().min(0).max(1e7).optional(),"C","microseconds"),schema8=exports_external.object({cache:CacheSchema,hit:HitSchema,key_hint:KeyHintSchema,latency_us:LatencyUsSchema}).strict()});var exports_cache_invalidate={};__export(exports_cache_invalidate,{schema:()=>schema9,TYPE:()=>TYPE8,SCHEMA_VERSION:()=>SCHEMA_VERSION8,KIND:()=>KIND8});var SCHEMA_VERSION8=1,TYPE8="cache.invalidate",KIND8="event",CacheSchema2,KeysInvalidatedSchema,ReasonSchema3,ScopeSchema,schema9;var init_cache_invalidate=__esm(()=>{init_zod();CacheSchema2=tagTier(exports_external.string().min(1).max(128),"C","cache name \u2014 public"),KeysInvalidatedSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),ReasonSchema3=tagTier(exports_external.enum(["ttl","manual","capacity","rotation","upstream_change"]).optional(),"C"),ScopeSchema=tagTier(exports_external.enum(["key","bucket","all"]).optional(),"C"),schema9=exports_external.object({cache:CacheSchema2,keys_invalidated:KeysInvalidatedSchema,reason:ReasonSchema3,scope:ScopeSchema}).strict()});var exports_cli_command={};__export(exports_cli_command,{schema:()=>schema10,TYPE:()=>TYPE9,SCHEMA_VERSION:()=>SCHEMA_VERSION9,KIND:()=>KIND9});var SCHEMA_VERSION9=1,TYPE9="cli.command",KIND9="span",CommandSchema,ArgsSchema,CwdSchema2,ExitCodeSchema,DurationSchema2,UserAgentSchema,schema10;var init_cli_command=__esm(()=>{init_zod();init_redactors();CommandSchema=tagTier(exports_external.string().max(256),"C","subcommand name only"),ArgsSchema=tagTier(exports_external.array(exports_external.string()).max(32).transform((args)=>args.map((a)=>redactFreeText(a))),"B","argv \u2014 secrets stripped, paths kept"),CwdSchema2=tagTier(exports_external.string().max(1024).transform(tokenizePath),"B","working directory tokenized"),ExitCodeSchema=tagTier(exports_external.number().int().min(-1).max(255),"C"),DurationSchema2=tagTier(exports_external.number().int().min(0).max(3600000),"C","milliseconds"),UserAgentSchema=tagTier(exports_external.string().max(256).optional(),"C"),schema10=exports_external.object({command:CommandSchema,args:ArgsSchema,cwd:CwdSchema2,exit_code:ExitCodeSchema.optional(),duration_ms:DurationSchema2.optional(),user_agent:UserAgentSchema}).strict().transform((v)=>({...v}))});var exports_consumer_heartbeat={};__export(exports_consumer_heartbeat,{schema:()=>schema11,TYPE:()=>TYPE10,SCHEMA_VERSION:()=>SCHEMA_VERSION10,KIND:()=>KIND10});var SCHEMA_VERSION10=1,TYPE10="consumer.heartbeat",KIND10="event",ConsumerIdSchema,LastEventIdSchema,BacklogDepthSchema,RoleSchema,UptimeSecondsSchema,schema11;var init_consumer_heartbeat=__esm(()=>{init_zod();init_redactors();ConsumerIdSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("consumer",v)),"A"),LastEventIdSchema=tagTier(exports_external.number().int().min(0).max(9007199254740991),"C"),BacklogDepthSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),RoleSchema=tagTier(exports_external.enum(["admin","operator","subscriber","audit"]).optional(),"C"),UptimeSecondsSchema=tagTier(exports_external.number().int().min(0).max(31536000).optional(),"C"),schema11=exports_external.object({consumer_id:ConsumerIdSchema,last_event_id_processed:LastEventIdSchema,backlog_depth:BacklogDepthSchema,role:RoleSchema,uptime_seconds:UptimeSecondsSchema}).strict()});var exports_consumer_lagged={};__export(exports_consumer_lagged,{schema:()=>schema12,TYPE:()=>TYPE11,SCHEMA_VERSION:()=>SCHEMA_VERSION11,KIND:()=>KIND11,DEFAULT_TIER:()=>DEFAULT_TIER3});var SCHEMA_VERSION11=1,TYPE11="consumer.lagged",KIND11="event",DEFAULT_TIER3="audit",CountSchema,SpillPathSchema,SeveritySchema,schema12;var init_consumer_lagged=__esm(()=>{init_zod();CountSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),SpillPathSchema=tagTier(exports_external.string().max(512),"B"),SeveritySchema=tagTier(exports_external.enum(["warn","error","fatal"]),"C"),schema12=exports_external.object({severity_class:SeveritySchema,spill_path:SpillPathSchema,rows_spilled:CountSchema,queue_depth:CountSchema,queue_cap:CountSchema}).strict()});var exports_correlation_orphan_rate={};__export(exports_correlation_orphan_rate,{schema:()=>schema13,TYPE:()=>TYPE12,SCHEMA_VERSION:()=>SCHEMA_VERSION12,KIND:()=>KIND12});var SCHEMA_VERSION12=1,TYPE12="correlation.orphan.rate",KIND12="event",RateSchema,CountSchema2,schema13;var init_correlation_orphan_rate=__esm(()=>{init_zod();RateSchema=tagTier(exports_external.number().min(0).max(1),"C"),CountSchema2=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema13=exports_external.object({window_samples:CountSchema2,orphans:CountSchema2,rate:RateSchema}).strict()});var exports_detector_disabled={};__export(exports_detector_disabled,{schema:()=>schema14,TYPE:()=>TYPE13,SCHEMA_VERSION:()=>SCHEMA_VERSION13,KIND:()=>KIND13});var SCHEMA_VERSION13=1,TYPE13="detector.disabled",KIND13="event",DetectorIdSchema,CauseSchema,BudgetSchema,FireCountSchema,BucketEndTsSchema,schema14;var init_detector_disabled=__esm(()=>{init_zod();DetectorIdSchema=tagTier(exports_external.string().min(1).max(128),"C"),CauseSchema=tagTier(exports_external.literal("fire_budget_exceeded"),"C"),BudgetSchema=tagTier(exports_external.number().int().min(1).max(1e6),"C","events per hour bucket"),FireCountSchema=tagTier(exports_external.number().int().min(0).max(1e6),"C","fires observed in this bucket"),BucketEndTsSchema=tagTier(exports_external.string().datetime({offset:!0}),"C","ISO-8601 timestamp when the current hour bucket expires"),schema14=exports_external.object({detector_id:DetectorIdSchema,cause:CauseSchema,budget:BudgetSchema,fire_count:FireCountSchema,bucket_end_ts:BucketEndTsSchema}).strict()});var exports_emit_backpressure_critical={};__export(exports_emit_backpressure_critical,{schema:()=>schema15,TYPE:()=>TYPE14,SCHEMA_VERSION:()=>SCHEMA_VERSION14,KIND:()=>KIND14,DEFAULT_TIER:()=>DEFAULT_TIER4});var SCHEMA_VERSION14=1,TYPE14="emit.backpressure.critical",KIND14="event",DEFAULT_TIER4="audit",SecondsSchema,CountSchema3,schema15;var init_emit_backpressure_critical=__esm(()=>{init_zod();SecondsSchema=tagTier(exports_external.number().min(0).max(86400),"C"),CountSchema3=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema15=exports_external.object({spill_duration_seconds:SecondsSchema,spill_rows_total:CountSchema3,queue_depth:CountSchema3,queue_cap:CountSchema3,recommended_action:tagTier(exports_external.enum(["scale_consumers","inspect_pg","restart_bridge"]).optional(),"C")}).strict()});var exports_emitter_latency_p99={};__export(exports_emitter_latency_p99,{schema:()=>schema16,TYPE:()=>TYPE15,SCHEMA_VERSION:()=>SCHEMA_VERSION15,KIND:()=>KIND15});var SCHEMA_VERSION15=1,TYPE15="emitter.latency_p99",KIND15="event",MillisSchema,SampleCountSchema,schema16;var init_emitter_latency_p99=__esm(()=>{init_zod();MillisSchema=tagTier(exports_external.number().min(0).max(600000),"C"),SampleCountSchema=tagTier(exports_external.number().int().min(1).max(1e6),"C"),schema16=exports_external.object({window_samples:SampleCountSchema,p50_ms:MillisSchema,p95_ms:MillisSchema,p99_ms:MillisSchema,max_ms:MillisSchema}).strict()});var exports_emitter_queue_depth={};__export(exports_emitter_queue_depth,{schema:()=>schema17,TYPE:()=>TYPE16,SCHEMA_VERSION:()=>SCHEMA_VERSION16,KIND:()=>KIND16});var SCHEMA_VERSION16=1,TYPE16="emitter.queue.depth",KIND16="event",DepthSchema,CapSchema,UtilizationSchema,schema17;var init_emitter_queue_depth=__esm(()=>{init_zod();DepthSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),CapSchema=tagTier(exports_external.number().int().min(1).max(1e7),"C"),UtilizationSchema=tagTier(exports_external.number().min(0).max(1),"C"),schema17=exports_external.object({depth:DepthSchema,cap:CapSchema,utilization:UtilizationSchema,enqueued_total:tagTier(exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER),"C"),flushed_total:tagTier(exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER),"C")}).strict()});var exports_emitter_rejected={};__export(exports_emitter_rejected,{schema:()=>schema18,TYPE:()=>TYPE17,SCHEMA_VERSION:()=>SCHEMA_VERSION17,KIND:()=>KIND17});var SCHEMA_VERSION17=1,TYPE17="emitter.rejected",KIND17="event",OffendingTypeSchema,ReasonSchema4,CountSchema4,schema18;var init_emitter_rejected=__esm(()=>{init_zod();OffendingTypeSchema=tagTier(exports_external.string().min(1).max(128),"C"),ReasonSchema4=tagTier(exports_external.enum(["schema_parse","unregistered","kind_mismatch","overflow_cap","queue_full"]),"C"),CountSchema4=tagTier(exports_external.number().int().min(1).max(1e7),"C"),schema18=exports_external.object({offending_type:OffendingTypeSchema,reason:ReasonSchema4,count:CountSchema4}).strict()});var exports_emitter_shedding_load={};__export(exports_emitter_shedding_load,{schema:()=>schema19,TYPE:()=>TYPE18,SCHEMA_VERSION:()=>SCHEMA_VERSION18,KIND:()=>KIND18});var SCHEMA_VERSION18=1,TYPE18="emitter.shedding_load",KIND18="event",CountSchema5,schema19;var init_emitter_shedding_load=__esm(()=>{init_zod();CountSchema5=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema19=exports_external.object({dropped_debug:CountSchema5,dropped_info:CountSchema5,spilled_warn_plus:CountSchema5,window_seconds:tagTier(exports_external.number().int().min(1).max(3600),"C")}).strict()});var exports_error_raised={};__export(exports_error_raised,{schema:()=>schema20,TYPE:()=>TYPE19,SCHEMA_VERSION:()=>SCHEMA_VERSION19,KIND:()=>KIND19});var SCHEMA_VERSION19=1,TYPE19="error.raised",KIND19="event",ErrorClassSchema,MessageSchema,StackSchema,SubsystemSchema,SeveritySchema2,RetryableSchema,schema20;var init_error_raised=__esm(()=>{init_zod();init_redactors();ErrorClassSchema=tagTier(exports_external.string().min(1).max(256),"C","exception class name"),MessageSchema=tagTier(exports_external.string().max(4096).transform(redactFreeText),"B"),StackSchema=tagTier(exports_external.string().max(16384).transform((stack)=>stack.split(`
|
|
685
685
|
`).map((line)=>tokenizePath(redactFreeText(line))).join(`
|
|
686
686
|
`)),"B","stack paths tokenized"),SubsystemSchema=tagTier(exports_external.string().min(1).max(128),"C"),SeveritySchema2=tagTier(exports_external.enum(["warn","error","fatal"]),"C"),RetryableSchema=tagTier(exports_external.boolean().optional(),"C"),schema20=exports_external.object({error_class:ErrorClassSchema,message:MessageSchema,stack:StackSchema.optional(),subsystem:SubsystemSchema,severity:SeveritySchema2,retryable:RetryableSchema}).strict()});var exports_executor_row_written={};__export(exports_executor_row_written,{schema:()=>schema21,TYPE:()=>TYPE20,SCHEMA_VERSION:()=>SCHEMA_VERSION20,KIND:()=>KIND20});var SCHEMA_VERSION20=1,TYPE20="executor.row.written",KIND20="event",TableSchema,RowIdSchema,OperationSchema,ExecutorSchema2,DiffSchema,schema21;var init_executor_row_written=__esm(()=>{init_zod();init_redactors();TableSchema=tagTier(exports_external.string().min(1).max(128),"C","PG table name \u2014 public"),RowIdSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("row",v)),"A"),OperationSchema=tagTier(exports_external.enum(["insert","update","delete","upsert"]),"C"),ExecutorSchema2=tagTier(exports_external.string().max(128).optional(),"C"),DiffSchema=tagTier(exports_external.record(exports_external.string(),exports_external.union([exports_external.string(),exports_external.number(),exports_external.boolean(),exports_external.null()])).default({}),"B","shallow scalar diff only \u2014 payloads never stored here"),schema21=exports_external.object({table:TableSchema,row_id:RowIdSchema,operation:OperationSchema,executor:ExecutorSchema2,before:DiffSchema,after:DiffSchema}).strict()});var exports_executor_write={};__export(exports_executor_write,{schema:()=>schema22,TYPE:()=>TYPE21,SCHEMA_VERSION:()=>SCHEMA_VERSION21,KIND:()=>KIND21});var SCHEMA_VERSION21=1,TYPE21="executor.write",KIND21="span",ExecutorSchema3,TargetSchema,TableSchema2,OperationSchema2,RowsAffectedSchema,DurationSchema3,OutcomeSchema,ErrorHintSchema,schema22;var init_executor_write=__esm(()=>{init_zod();init_redactors();ExecutorSchema3=tagTier(exports_external.enum(["claude-code","claude-sdk","codex","shell"]),"C"),TargetSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("executor_target",v)),"A","target entity hashed"),TableSchema2=tagTier(exports_external.string().max(128).optional(),"C","PG table name \u2014 public"),OperationSchema2=tagTier(exports_external.enum(["insert","update","delete","upsert","copy","truncate"]),"C"),RowsAffectedSchema=tagTier(exports_external.number().int().min(0).max(1e7).optional(),"C"),DurationSchema3=tagTier(exports_external.number().int().min(0).max(60000).optional(),"C","ms"),OutcomeSchema=tagTier(exports_external.enum(["ok","constraint_violation","timeout","error"]).optional(),"C"),ErrorHintSchema=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)).optional(),"B"),schema22=exports_external.object({executor:ExecutorSchema3,target:TargetSchema,table:TableSchema2,operation:OperationSchema2,rows_affected:RowsAffectedSchema,duration_ms:DurationSchema3,outcome:OutcomeSchema,error_hint:ErrorHintSchema}).strict()});var exports_hook_delivery={};__export(exports_hook_delivery,{schema:()=>schema23,TYPE:()=>TYPE22,SCHEMA_VERSION:()=>SCHEMA_VERSION22,KIND:()=>KIND22});var SCHEMA_VERSION22=1,TYPE22="hook.delivery",KIND22="span",HookNameSchema,HookEventSchema,AgentIdSchema2,ToolSchema,StatusSchema,DurationSchema4,ExitCodeSchema2,StderrExcerptSchema,schema23;var init_hook_delivery=__esm(()=>{init_zod();init_redactors();HookNameSchema=tagTier(exports_external.string().min(1).max(128),"C","hook name \u2014 public"),HookEventSchema=tagTier(exports_external.string().min(1).max(64),"C","CC hook event name \u2014 public"),AgentIdSchema2=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),ToolSchema=tagTier(exports_external.string().max(128).optional(),"C"),StatusSchema=tagTier(exports_external.enum(["ok","timeout","rejected","error"]).optional(),"C"),DurationSchema4=tagTier(exports_external.number().int().min(0).max(60000).optional(),"C","ms (<=15s timeout)"),ExitCodeSchema2=tagTier(exports_external.number().int().min(-1).max(255).optional(),"C"),StderrExcerptSchema=tagTier(exports_external.string().max(4096).transform((v)=>redactFreeText(v)).optional(),"B","redacted stderr excerpt"),schema23=exports_external.object({hook_name:HookNameSchema,agent_id:AgentIdSchema2,tool:ToolSchema,event:HookEventSchema.optional(),status:StatusSchema,duration_ms:DurationSchema4,exit_code:ExitCodeSchema2,stderr_excerpt:StderrExcerptSchema}).strict()});var exports_mailbox_delivery={};__export(exports_mailbox_delivery,{schema:()=>schema24,TYPE:()=>TYPE23,SCHEMA_VERSION:()=>SCHEMA_VERSION23,KIND:()=>KIND23});var SCHEMA_VERSION23=1,TYPE23="mailbox.delivery",KIND23="span",AgentIdSchema3=(ns)=>tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity(ns,v)),"A"),FromSchema,ToSchema,ChannelSchema,OutcomeSchema2,MessageIdSchema,BodyExcerptSchema,DurationSchema5,schema24;var init_mailbox_delivery=__esm(()=>{init_zod();init_redactors();FromSchema=tagTier(exports_external.string().max(128),"C","sender role \u2014 public"),ToSchema=tagTier(exports_external.string().max(128),"C","recipient role \u2014 public"),ChannelSchema=tagTier(exports_external.enum(["tmux","native-inbox","file","broadcast"]),"C"),OutcomeSchema2=tagTier(exports_external.enum(["delivered","queued","pane_dead","rejected","timeout"]).optional(),"C"),MessageIdSchema=AgentIdSchema3("msg").optional(),BodyExcerptSchema=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)).optional(),"B","first 512 chars, redacted"),DurationSchema5=tagTier(exports_external.number().int().min(0).max(60000).optional(),"C","ms"),schema24=exports_external.object({from:FromSchema,to:ToSchema,channel:ChannelSchema,outcome:OutcomeSchema2,message_id:MessageIdSchema,body_excerpt:BodyExcerptSchema,duration_ms:DurationSchema5}).strict()});var exports_notify_delivery_lag={};__export(exports_notify_delivery_lag,{schema:()=>schema25,TYPE:()=>TYPE24,SCHEMA_VERSION:()=>SCHEMA_VERSION24,KIND:()=>KIND24});var SCHEMA_VERSION24=1,TYPE24="notify.delivery.lag",KIND24="event",NonceSchema,LagMillisSchema,ChannelSchema2,schema25;var init_notify_delivery_lag=__esm(()=>{init_zod();init_redactors();NonceSchema=tagTier(exports_external.string().min(1).max(128).transform((v)=>hashEntity("notify-probe",v)),"A"),LagMillisSchema=tagTier(exports_external.number().min(0).max(300000),"C"),ChannelSchema2=tagTier(exports_external.string().min(1).max(128),"C"),schema25=exports_external.object({channel:ChannelSchema2,probe_id:NonceSchema,lag_ms:LagMillisSchema,timed_out:tagTier(exports_external.boolean(),"C")}).strict()});var exports_permissions_deny={};__export(exports_permissions_deny,{schema:()=>schema26,TYPE:()=>TYPE25,SCHEMA_VERSION:()=>SCHEMA_VERSION25,KIND:()=>KIND25});var SCHEMA_VERSION25=1,TYPE25="permissions.deny",KIND25="event",ActorSchema,AttemptedRoleSchema,ScopeSchema2,ReasonSchema5,SourceIpSchema,schema26;var init_permissions_deny=__esm(()=>{init_zod();init_redactors();ActorSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A"),AttemptedRoleSchema=tagTier(exports_external.string().min(1).max(64),"C"),ScopeSchema2=tagTier(exports_external.string().min(1).max(128),"C"),ReasonSchema5=tagTier(exports_external.enum(["token_expired","token_invalid","signature_invalid","scope_mismatch","tenant_mismatch","rate_limited","revoked","unknown"]),"C"),SourceIpSchema=tagTier(exports_external.string().max(64).transform((v)=>hashEntity("ip",v)).optional(),"A"),schema26=exports_external.object({actor:ActorSchema,attempted_role:AttemptedRoleSchema,scope:ScopeSchema2,reason:ReasonSchema5,source_ip:SourceIpSchema}).strict()});var exports_permissions_grant={};__export(exports_permissions_grant,{schema:()=>schema27,TYPE:()=>TYPE26,SCHEMA_VERSION:()=>SCHEMA_VERSION26,KIND:()=>KIND26});var SCHEMA_VERSION26=1,TYPE26="permissions.grant",KIND26="event",ActorSchema2,RoleSchema2,ScopeSchema3,ExpiresAtSchema,GrantedBySchema,schema27;var init_permissions_grant=__esm(()=>{init_zod();init_redactors();ActorSchema2=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A"),RoleSchema2=tagTier(exports_external.enum(["admin","operator","subscriber","audit"]),"C"),ScopeSchema3=tagTier(exports_external.string().min(1).max(128),"C",'e.g. "genie_events.agent.*" \u2014 public'),ExpiresAtSchema=tagTier(exports_external.string().datetime().optional(),"C"),GrantedBySchema=tagTier(exports_external.string().max(256).transform((v)=>hashEntity("actor",v)).optional(),"A"),schema27=exports_external.object({actor:ActorSchema2,role:RoleSchema2,scope:ScopeSchema3,expires_at:ExpiresAtSchema,granted_by:GrantedBySchema}).strict()});var exports_resume_attempt={};__export(exports_resume_attempt,{schema:()=>schema28,TYPE:()=>TYPE27,SCHEMA_VERSION:()=>SCHEMA_VERSION27,KIND:()=>KIND27});var SCHEMA_VERSION27=1,TYPE27="resume.attempt",KIND27="span",AgentIdSchema4,AttemptNumberSchema4,StrategySchema,SessionIdSchema2,SucceededSchema,FailureReasonSchema,DurationSchema6,schema28;var init_resume_attempt=__esm(()=>{init_zod();init_redactors();AgentIdSchema4=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),AttemptNumberSchema4=tagTier(exports_external.number().int().min(1).max(16),"C"),StrategySchema=tagTier(exports_external.enum(["tmux-attach","claude-resume-session","cold-start","session-backfill"]),"C"),SessionIdSchema2=tagTier(exports_external.string().max(128).transform((v)=>hashEntity("session",v)).optional(),"A"),SucceededSchema=tagTier(exports_external.boolean().optional(),"C"),FailureReasonSchema=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)).optional(),"B"),DurationSchema6=tagTier(exports_external.number().int().min(0).max(300000).optional(),"C","ms"),schema28=exports_external.object({agent_id:AgentIdSchema4,attempt_number:AttemptNumberSchema4,strategy:StrategySchema,session_id:SessionIdSchema2,succeeded:SucceededSchema,failure_reason:FailureReasonSchema,duration_ms:DurationSchema6}).strict()});var exports_rot_detected={};__export(exports_rot_detected,{schema:()=>schema29,TYPE:()=>TYPE28,SCHEMA_VERSION:()=>SCHEMA_VERSION28,KIND:()=>KIND28});var SCHEMA_VERSION28=1,TYPE28="rot.detected",KIND28="event",PatternIdSchema,EntityIdSchema4,ObservedValueSchema,ObservedStateSchema,schema29;var init_rot_detected=__esm(()=>{init_zod();init_redactors();PatternIdSchema=tagTier(exports_external.string().min(1).max(128).regex(/^[a-z0-9][a-z0-9._-]*$/,"pattern_id must be kebab/dot/underscore lowercase"),"C"),EntityIdSchema4=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("entity",v)),"A"),ObservedValueSchema=tagTier(exports_external.union([exports_external.string().max(4096).transform(redactFreeText),exports_external.number().finite(),exports_external.boolean(),exports_external.null(),exports_external.array(exports_external.string().max(1024).transform(redactFreeText)).max(256),exports_external.array(exports_external.number().finite()).max(256)]),"B","evidence scalar \u2014 free text runs through redactFreeText"),ObservedStateSchema=tagTier(exports_external.record(exports_external.string().min(1).max(64).regex(/^[a-z0-9_]+$/,"observed_state key must be snake_case"),ObservedValueSchema).refine((obj)=>Object.keys(obj).length<=32,{message:"observed_state_json cannot exceed 32 keys"}),"B","per-pattern evidence record \u2014 keys documented by each detector module"),schema29=exports_external.object({pattern_id:PatternIdSchema,entity_id:EntityIdSchema4,observed_state_json:ObservedStateSchema}).strict()});var exports_rot_executor_ghost_detected={};__export(exports_rot_executor_ghost_detected,{schema:()=>schema30,TYPE:()=>TYPE29,SCHEMA_VERSION:()=>SCHEMA_VERSION29,KIND:()=>KIND29});var SCHEMA_VERSION29=1,TYPE29="rot.executor-ghost.detected",KIND29="event",ResolutionSourceSchema,EnvIdSchema,ResolvedIdSchema,AgentNameSchema,RecoveredSchema,schema30;var init_rot_executor_ghost_detected=__esm(()=>{init_zod();ResolutionSourceSchema=tagTier(exports_external.enum(["resolver","reconciler"]),"C"),EnvIdSchema=tagTier(exports_external.string().uuid(),"C"),ResolvedIdSchema=tagTier(exports_external.string().uuid(),"C"),AgentNameSchema=tagTier(exports_external.string().min(1).max(256),"C"),RecoveredSchema=tagTier(exports_external.boolean(),"C"),schema30=exports_external.object({resolution_source:ResolutionSourceSchema,env_id:EnvIdSchema,resolved_id:ResolvedIdSchema,agent_name:AgentNameSchema,recovered:RecoveredSchema}).strict()});var exports_rot_inbox_watcher_spawn_loop_detected={};__export(exports_rot_inbox_watcher_spawn_loop_detected,{schema:()=>schema31,TYPE:()=>TYPE30,SCHEMA_VERSION:()=>SCHEMA_VERSION30,KIND:()=>KIND30});var SCHEMA_VERSION30=1,TYPE30="rot.inbox-watcher-spawn-loop.detected",KIND30="event",TeamNameSchema,SessionKeySchema,FailureCountSchema,LastErrorMessageSchema,schema31;var init_rot_inbox_watcher_spawn_loop_detected=__esm(()=>{init_zod();init_redactors();TeamNameSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>redactFreeText(v)),"C"),SessionKeySchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>redactFreeText(v)),"C"),FailureCountSchema=tagTier(exports_external.number().int().min(1).max(100),"C"),LastErrorMessageSchema=tagTier(exports_external.string().min(1).max(2048).transform((v)=>redactFreeText(v)),"B","redacted error message from the final failed ensureTeamLead() call"),schema31=exports_external.object({team_name:TeamNameSchema,session_key:SessionKeySchema,failure_count:FailureCountSchema,last_error_message:LastErrorMessageSchema}).strict()});var exports_rot_team_ls_drift_detected={};__export(exports_rot_team_ls_drift_detected,{schema:()=>schema32,TYPE:()=>TYPE31,SCHEMA_VERSION:()=>SCHEMA_VERSION31,KIND:()=>KIND31});var SCHEMA_VERSION31=1,TYPE31="rot.team-ls-drift.detected",KIND31="event",DivergenceKindSchema,DivergentCountSchema,ObservedStateJsonSchema,ObservedStateJsonTruncatedSchema,schema32;var init_rot_team_ls_drift_detected=__esm(()=>{init_zod();init_redactors();DivergenceKindSchema=tagTier(exports_external.enum(["missing_in_disband","missing_in_ls","status_mismatch"]),"C"),DivergentCountSchema=tagTier(exports_external.number().int().min(1).max(1e4),"C"),ObservedStateJsonSchema=tagTier(exports_external.string().min(2).max(16384).transform((v)=>redactFreeText(v)),"B","JSON-encoded snapshot of both data sources for triage"),ObservedStateJsonTruncatedSchema=tagTier(exports_external.literal(!0).optional(),"C","set when detail was dropped to honor the observed_state_json cap"),schema32=exports_external.object({divergence_kind:DivergenceKindSchema,divergent_count:DivergentCountSchema,observed_state_json:ObservedStateJsonSchema,observed_state_json_truncated:ObservedStateJsonTruncatedSchema}).strict()});var exports_runbook_triggered={};__export(exports_runbook_triggered,{schema:()=>schema33,TYPE:()=>TYPE32,SCHEMA_VERSION:()=>SCHEMA_VERSION32,KIND:()=>KIND32});var SCHEMA_VERSION32=1,TYPE32="runbook.triggered",KIND32="event",RuleSchema,EvidenceCountSchema,CorrelationIdSchema,WindowMinutesSchema,RecommendedSqlSchema,EvidenceSummarySchema,schema33;var init_runbook_triggered=__esm(()=>{init_zod();init_redactors();RuleSchema=tagTier(exports_external.string().min(1).max(64).regex(/^R\d+$/,"rule id must be R<int>"),"C"),EvidenceCountSchema=tagTier(exports_external.number().int().min(1).max(1e6),"C"),CorrelationIdSchema=tagTier(exports_external.string().max(128).transform((v)=>hashEntity("trace",v)).optional(),"A"),WindowMinutesSchema=tagTier(exports_external.number().int().min(1).max(1440).optional(),"C"),RecommendedSqlSchema=tagTier(exports_external.string().max(4096).transform((v)=>redactFreeText(v)).optional(),"B","mitigation SQL \u2014 redacted free text"),EvidenceSummarySchema=tagTier(exports_external.string().max(1024).transform((v)=>redactFreeText(v)).optional(),"B"),schema33=exports_external.object({rule:RuleSchema,evidence_count:EvidenceCountSchema,window_minutes:WindowMinutesSchema,correlation_id:CorrelationIdSchema,recommended_sql:RecommendedSqlSchema,evidence_summary:EvidenceSummarySchema}).strict()});var exports_schema_violation={};__export(exports_schema_violation,{schema:()=>schema34,TYPE:()=>TYPE33,SCHEMA_VERSION:()=>SCHEMA_VERSION33,KIND:()=>KIND33});var SCHEMA_VERSION33=1,TYPE33="schema.violation",KIND33="event",OffendingTypeSchema2,RejectedBytesSchema,IssueSchema,schema34;var init_schema_violation=__esm(()=>{init_zod();init_redactors();OffendingTypeSchema2=tagTier(exports_external.string().min(1).max(128),"C"),RejectedBytesSchema=tagTier(exports_external.number().int().min(0).max(1048576),"C"),IssueSchema=tagTier(exports_external.object({path:exports_external.string().max(256),code:exports_external.string().max(64),message:exports_external.string().max(512).transform(redactFreeText)}),"B"),schema34=exports_external.object({offending_type:OffendingTypeSchema2,issues:tagTier(exports_external.array(IssueSchema).max(32),"B"),rejected_bytes:RejectedBytesSchema,source_subsystem:tagTier(exports_external.string().max(128).optional(),"C")}).strict()});var exports_session_id_written={};__export(exports_session_id_written,{schema:()=>schema35,TYPE:()=>TYPE34,SCHEMA_VERSION:()=>SCHEMA_VERSION34,KIND:()=>KIND34});var SCHEMA_VERSION34=1,TYPE34="session.id.written",KIND34="event",AgentIdSchema5,SessionIdSchema3,ExecutorSchema4,OriginSchema,DiffSchema2,schema35;var init_session_id_written=__esm(()=>{init_zod();init_redactors();AgentIdSchema5=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),SessionIdSchema3=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("session",v)),"A"),ExecutorSchema4=tagTier(exports_external.enum(["claude-code","claude-sdk","codex","shell"]),"C"),OriginSchema=tagTier(exports_external.enum(["spawn","resume","backfill","reconcile"]),"C"),DiffSchema2=tagTier(exports_external.record(exports_external.string(),exports_external.union([exports_external.string(),exports_external.number(),exports_external.boolean(),exports_external.null()])).default({}),"B","shallow scalar diff \u2014 session_id hashed before arriving here"),schema35=exports_external.object({agent_id:AgentIdSchema5,session_id:SessionIdSchema3,executor:ExecutorSchema4,origin:OriginSchema,before:DiffSchema2,after:DiffSchema2}).strict()});var exports_session_reconciled={};__export(exports_session_reconciled,{schema:()=>schema36,TYPE:()=>TYPE35,SCHEMA_VERSION:()=>SCHEMA_VERSION35,KIND:()=>KIND35});var SCHEMA_VERSION35=1,TYPE35="session.reconciled",KIND35="event",AgentIdSchema6,SessionIdSchema4,ReasonSchema6,DiffSchema3,schema36;var init_session_reconciled=__esm(()=>{init_zod();init_redactors();AgentIdSchema6=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),SessionIdSchema4=tagTier(exports_external.string().max(256).transform((v)=>hashEntity("session",v)),"A"),ReasonSchema6=tagTier(exports_external.enum(["transcript-discovered","stale-pg-session","idle-timeout","manual","backfill"]),"C"),DiffSchema3=tagTier(exports_external.record(exports_external.string(),exports_external.union([exports_external.string(),exports_external.number(),exports_external.boolean(),exports_external.null()])).default({}),"B"),schema36=exports_external.object({agent_id:AgentIdSchema6,old_session_id:SessionIdSchema4.optional(),new_session_id:SessionIdSchema4,reason:ReasonSchema6,before:DiffSchema3,after:DiffSchema3}).strict()});var exports_state_transition={};__export(exports_state_transition,{schema:()=>schema37,TYPE:()=>TYPE36,SCHEMA_VERSION:()=>SCHEMA_VERSION36,KIND:()=>KIND36});var SCHEMA_VERSION36=1,TYPE36="state_transition",KIND36="event",EntityKindSchema,EntityIdSchema5,FromSchema2,ToSchema2,ReasonSchema7,ActorSchema3,DiffSchema4,schema37;var init_state_transition=__esm(()=>{init_zod();init_redactors();EntityKindSchema=tagTier(exports_external.enum(["task","wish","worker","team","team_lead","group","mailbox_message"]),"C"),EntityIdSchema5=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("entity",v)),"A","entity id hashed"),FromSchema2=tagTier(exports_external.string().min(1).max(64),"C"),ToSchema2=tagTier(exports_external.string().min(1).max(64),"C"),ReasonSchema7=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)).optional(),"B","redacted free-text"),ActorSchema3=tagTier(exports_external.string().max(128).transform((v)=>redactFreeText(v)).optional(),"B"),DiffSchema4=tagTier(exports_external.record(exports_external.string(),exports_external.union([exports_external.string(),exports_external.number(),exports_external.boolean(),exports_external.null()])).default({}),"B","shallow scalar diff only"),schema37=exports_external.object({entity_kind:EntityKindSchema,entity_id:EntityIdSchema5,from:FromSchema2,to:ToSchema2,reason:ReasonSchema7,actor:ActorSchema3,before:DiffSchema4,after:DiffSchema4}).strict()});var exports_stream_gap_detected={};__export(exports_stream_gap_detected,{schema:()=>schema38,TYPE:()=>TYPE37,SCHEMA_VERSION:()=>SCHEMA_VERSION37,KIND:()=>KIND37});var SCHEMA_VERSION37=1,TYPE37="stream.gap.detected",KIND37="event",ConsumerIdSchema2,IdSchema,CountSchema6,schema38;var init_stream_gap_detected=__esm(()=>{init_zod();init_redactors();ConsumerIdSchema2=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("consumer",v)),"A"),IdSchema=tagTier(exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER),"C"),CountSchema6=tagTier(exports_external.number().int().min(1).max(1e7),"C"),schema38=exports_external.object({consumer_id:ConsumerIdSchema2,from_id:IdSchema,to_id:IdSchema,missing_count:CountSchema6}).strict()});var exports_team_create={};__export(exports_team_create,{schema:()=>schema39,TYPE:()=>TYPE38,SCHEMA_VERSION:()=>SCHEMA_VERSION38,KIND:()=>KIND38,DEFAULT_TIER:()=>DEFAULT_TIER5});var SCHEMA_VERSION38=1,TYPE38="team.create",KIND38="event",DEFAULT_TIER5="audit",TeamNameSchema2,WishSlugSchema,RepoPathHashSchema,ActorSchema4,MemberCountSchema,AutoSchema,schema39;var init_team_create=__esm(()=>{init_zod();init_redactors();TeamNameSchema2=tagTier(exports_external.string().min(1).max(128),"C","team name \u2014 public label"),WishSlugSchema=tagTier(exports_external.string().max(128).optional(),"C"),RepoPathHashSchema=tagTier(exports_external.string().min(1).max(1024).transform((v)=>hashEntity("repo",v)),"A"),ActorSchema4=tagTier(exports_external.string().max(256).transform((v)=>hashEntity("actor",v)),"A"),MemberCountSchema=tagTier(exports_external.number().int().min(0).max(256).optional(),"C"),AutoSchema=tagTier(exports_external.boolean().optional(),"C","true if created by auto-spawn hook"),schema39=exports_external.object({team_name:TeamNameSchema2,wish_slug:WishSlugSchema,repo_path_hash:RepoPathHashSchema,actor:ActorSchema4,member_count:MemberCountSchema,auto:AutoSchema}).strict()});var exports_team_disband={};__export(exports_team_disband,{schema:()=>schema40,TYPE:()=>TYPE39,SCHEMA_VERSION:()=>SCHEMA_VERSION39,KIND:()=>KIND39,DEFAULT_TIER:()=>DEFAULT_TIER6});var SCHEMA_VERSION39=1,TYPE39="team.disband",KIND39="event",DEFAULT_TIER6="audit",TeamNameSchema3,ActorSchema5,RemainingMembersSchema,ReasonSchema8,schema40;var init_team_disband=__esm(()=>{init_zod();init_redactors();TeamNameSchema3=tagTier(exports_external.string().min(1).max(128),"C"),ActorSchema5=tagTier(exports_external.string().max(256).transform((v)=>hashEntity("actor",v)).optional(),"A"),RemainingMembersSchema=tagTier(exports_external.number().int().min(0).max(256).optional(),"C"),ReasonSchema8=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)).optional(),"B"),schema40=exports_external.object({team_name:TeamNameSchema3,actor:ActorSchema5,remaining_members:RemainingMembersSchema,reason:ReasonSchema8}).strict()});var exports_tmux_pane_placed={};__export(exports_tmux_pane_placed,{schema:()=>schema41,TYPE:()=>TYPE40,SCHEMA_VERSION:()=>SCHEMA_VERSION40,KIND:()=>KIND40});var SCHEMA_VERSION40=1,TYPE40="tmux.pane.placed",KIND40="event",AgentIdSchema7,SessionSchema,WindowIndexSchema,PaneIndexSchema,PaneIdSchema,ActionSchema,schema41;var init_tmux_pane_placed=__esm(()=>{init_zod();init_redactors();AgentIdSchema7=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),SessionSchema=tagTier(exports_external.string().min(1).max(128),"C","tmux session name \u2014 public"),WindowIndexSchema=tagTier(exports_external.number().int().min(0).max(256),"C"),PaneIndexSchema=tagTier(exports_external.number().int().min(0).max(256),"C"),PaneIdSchema=tagTier(exports_external.string().max(64).optional(),"C","tmux pane id \u2014 public"),ActionSchema=tagTier(exports_external.enum(["spawn","attach","replace","split"]),"C"),schema41=exports_external.object({agent_id:AgentIdSchema7,session:SessionSchema,window_index:WindowIndexSchema,pane_index:PaneIndexSchema,pane_id:PaneIdSchema,action:ActionSchema}).strict()});var exports_wish_dispatch={};__export(exports_wish_dispatch,{schema:()=>schema42,TYPE:()=>TYPE41,SCHEMA_VERSION:()=>SCHEMA_VERSION41,KIND:()=>KIND41});var SCHEMA_VERSION41=1,TYPE41="wish.dispatch",KIND41="span",WishSlugSchema2,WaveSchema,GroupIdSchema,GroupNameSchema,ActorSchema6,OutcomeSchema3,DurationSchema7,DryRunSchema,schema42;var init_wish_dispatch=__esm(()=>{init_zod();init_redactors();WishSlugSchema2=tagTier(exports_external.string().min(1).max(128),"C","wish slug \u2014 public"),WaveSchema=tagTier(exports_external.number().int().min(0).max(32),"C"),GroupIdSchema=tagTier(exports_external.string().min(1).max(128).transform((v)=>hashEntity("group",v)),"A","group id hashed"),GroupNameSchema=tagTier(exports_external.string().max(128),"C"),ActorSchema6=tagTier(exports_external.string().max(128).transform((v)=>redactFreeText(v)).optional(),"B"),OutcomeSchema3=tagTier(exports_external.enum(["started","completed","failed","blocked"]).optional(),"C"),DurationSchema7=tagTier(exports_external.number().int().min(0).max(86400000).optional(),"C","ms"),DryRunSchema=tagTier(exports_external.boolean().optional(),"C"),schema42=exports_external.object({wish_slug:WishSlugSchema2,wave:WaveSchema.optional(),group_id:GroupIdSchema.optional(),group_name:GroupNameSchema.optional(),actor:ActorSchema6,outcome:OutcomeSchema3,duration_ms:DurationSchema7,dry_run:DryRunSchema}).strict()});function entry(mod){return{type:mod.TYPE,kind:mod.KIND,schema:mod.schema,schema_version:mod.SCHEMA_VERSION,tier_defaults:mod.DEFAULT_TIER??"default"}}function getEntry(type2){return EventRegistry[type2]??null}function isRegistered(type2){return Object.hasOwn(EventRegistry,type2)}var EventRegistry;var init_registry=__esm(()=>{init_agent_lifecycle();init_agent_resume_attempted();init_agent_resume_failed();init_agent_resume_succeeded();init_audit_export();init_audit_un_hash();init_cache_hit();init_cache_invalidate();init_cli_command();init_consumer_heartbeat();init_consumer_lagged();init_correlation_orphan_rate();init_detector_disabled();init_emit_backpressure_critical();init_emitter_latency_p99();init_emitter_queue_depth();init_emitter_rejected();init_emitter_shedding_load();init_error_raised();init_executor_row_written();init_executor_write();init_hook_delivery();init_mailbox_delivery();init_notify_delivery_lag();init_permissions_deny();init_permissions_grant();init_resume_attempt();init_rot_detected();init_rot_executor_ghost_detected();init_rot_inbox_watcher_spawn_loop_detected();init_rot_team_ls_drift_detected();init_runbook_triggered();init_schema_violation();init_session_id_written();init_session_reconciled();init_state_transition();init_stream_gap_detected();init_team_create();init_team_disband();init_tmux_pane_placed();init_wish_dispatch();EventRegistry={[TYPE9]:entry(exports_cli_command),[TYPE]:entry(exports_agent_lifecycle),[TYPE41]:entry(exports_wish_dispatch),[TYPE22]:entry(exports_hook_delivery),[TYPE27]:entry(exports_resume_attempt),[TYPE21]:entry(exports_executor_write),[TYPE23]:entry(exports_mailbox_delivery),[TYPE19]:entry(exports_error_raised),[TYPE36]:entry(exports_state_transition),[TYPE33]:entry(exports_schema_violation),[TYPE34]:entry(exports_session_id_written),[TYPE35]:entry(exports_session_reconciled),[TYPE40]:entry(exports_tmux_pane_placed),[TYPE20]:entry(exports_executor_row_written),[TYPE8]:entry(exports_cache_invalidate),[TYPE7]:entry(exports_cache_hit),[TYPE32]:entry(exports_runbook_triggered),[TYPE10]:entry(exports_consumer_heartbeat),[TYPE26]:entry(exports_permissions_grant),[TYPE25]:entry(exports_permissions_deny),[TYPE38]:entry(exports_team_create),[TYPE39]:entry(exports_team_disband),[TYPE6]:entry(exports_audit_un_hash),[TYPE5]:entry(exports_audit_export),[TYPE17]:entry(exports_emitter_rejected),[TYPE16]:entry(exports_emitter_queue_depth),[TYPE15]:entry(exports_emitter_latency_p99),[TYPE24]:entry(exports_notify_delivery_lag),[TYPE37]:entry(exports_stream_gap_detected),[TYPE12]:entry(exports_correlation_orphan_rate),[TYPE18]:entry(exports_emitter_shedding_load),[TYPE11]:entry(exports_consumer_lagged),[TYPE14]:entry(exports_emit_backpressure_critical),[TYPE13]:entry(exports_detector_disabled),[TYPE28]:entry(exports_rot_detected),[TYPE31]:entry(exports_rot_team_ls_drift_detected),[TYPE29]:entry(exports_rot_executor_ghost_detected),[TYPE30]:entry(exports_rot_inbox_watcher_spawn_loop_detected),[TYPE2]:entry(exports_agent_resume_attempted),[TYPE4]:entry(exports_agent_resume_succeeded),[TYPE3]:entry(exports_agent_resume_failed)}});var exports_emit={};__export(exports_emit,{startSpan:()=>startSpan,shutdownEmitter:()=>shutdownEmitter,resumeEmitter:()=>resumeEmitter,isSpillJournalEmpty:()=>isSpillJournalEmpty,getEmitStats:()=>getEmitStats,flushNow:()=>flushNow,endSpan:()=>endSpan,emitEvent:()=>emitEvent,drainSpillJournalNow:()=>drainSpillJournalNow,__setSpillPathForTests:()=>__setSpillPathForTests,__resetEmitForTests:()=>__resetEmitForTests,__TEST_QUEUE_CAP:()=>__TEST_QUEUE_CAP,__TEST_BACKPRESSURE_WAIT_MS:()=>__TEST_BACKPRESSURE_WAIT_MS});import{createHash as createHash2,randomUUID as randomUUID3}from"crypto";import{appendFileSync,closeSync,existsSync as existsSync14,fsyncSync,mkdirSync as mkdirSync7,openSync,readFileSync as readFileSync10,renameSync as renameSync2,statSync as statSync2,unlinkSync as unlinkSync4}from"fs";import{homedir as homedir13}from"os";import{dirname as dirname5,join as join18}from"path";function getEmitStats(){return{...stats,queue_depth:queue.length}}function defaultSpillPath(){let home=process.env.GENIE_HOME??join18(homedir13(),".genie");return join18(home,"data","emit-spill.jsonl")}function __setSpillPathForTests(path2){spillPathOverride=path2}function spillPath(){return spillPathOverride??defaultSpillPath()}function ensureSpillDir(path2){let dir=dirname5(path2);if(!existsSync14(dir))mkdirSync7(dir,{recursive:!0})}function writeSpillRow(row){let path2=spillPath();ensureSpillDir(path2);let line=`${JSON.stringify(row)}
|
|
687
687
|
`,fd=openSync(path2,"a");try{appendFileSync(fd,line);try{fsyncSync(fd)}catch{}}finally{closeSync(fd)}if(stats.spilled_warn_plus++,firstSpillAt===null)firstSpillAt=Date.now()}function countSpillRows(){let path2=spillPath();if(!existsSync14(path2))return 0;try{let contents=readFileSync10(path2,"utf8");if(!contents)return 0;return contents.split(`
|
|
@@ -2208,7 +2208,7 @@ ${body}`;writeFileSync14(filePath,output,"utf-8")}function serializeSdkConfig(sd
|
|
|
2208
2208
|
'scheduler',
|
|
2209
2209
|
${tx.json({agent_id:worker.id,reason,outcome:"clean_exit_unverified"})}
|
|
2210
2210
|
)
|
|
2211
|
-
`,{terminalized:!0,executorId}})}catch(err){let message=err instanceof Error?err.message:String(err);return deps.log({timestamp:deps.now().toISOString(),level:"error",event:"terminalize_clean_exit_unverified_failed",agent_id:worker.id,error:message}),{terminalized:!1,executorId:null}}}async function reconcileUnresumable(deps){let workers=await deps.listWorkers(),flipped=0;for(let worker of workers){if(worker.state!=="error")continue;if(worker.autoResume===!1)continue;if(worker.currentSessionId)continue;try{await deps.updateAgent(worker.id,{autoResume:!1}),deps.log({timestamp:deps.now().toISOString(),level:"warn",event:"agent_marked_unresumable",agent_id:worker.id,reason:"no_session_id",state:worker.state}),flipped++}catch(err){let message=err instanceof Error?err.message:String(err);deps.log({timestamp:deps.now().toISOString(),level:"warn",event:"agent_marked_unresumable_failed",agent_id:worker.id,error:message})}}return flipped}async function countActiveWorkers(workers,isPaneAlive2){let count=0;for(let w of workers){if(w.state==null||INACTIVE_WORKER_STATES.has(w.state))continue;if(/^%\d+$/.test(w.paneId))try{if(!await isPaneAlive2(w.paneId))continue}catch{}count++}return count}function telemetryState(raw){return raw&&TELEMETRY_STATES.has(raw)?raw:"unknown"}function recordResumeTelemetry(eventType,payload,actor){recordAuditEvent("agent.resume",payload.entity_id,eventType,actor,payload).catch(()=>{});try{let v2Payload={entity_id:payload.entity_id,attempt_number:payload.attempt_number,state_before:payload.state_before,state_after:payload.state_after,trigger:payload.trigger};if(payload.last_error)v2Payload.last_error=payload.last_error.slice(0,500);if(eventType==="agent.resume.failed")v2Payload.exhausted=payload.exhausted??!1;emitEvent(eventType,v2Payload,{severity:eventType==="agent.resume.failed"?"warn":"info",source_subsystem:"scheduler.auto-resume"})}catch{}}async function attemptAgentResume(deps,config,agent){let now=deps.now(),agentId=agent.id;if(agent.autoResume===!1)return deps.log({timestamp:now.toISOString(),level:"debug",event:"agent_resume_skipped",agent_id:agentId,reason:"auto_resume_disabled"}),"skipped";let maxAttempts=agent.maxResumeAttempts??DEFAULT_MAX_RESUME_ATTEMPTS,attempts=agent.resumeAttempts??0;if(!agent.currentSessionId){let newAttempts2=attempts+1;
|
|
2211
|
+
`,{terminalized:!0,executorId}})}catch(err){let message=err instanceof Error?err.message:String(err);return deps.log({timestamp:deps.now().toISOString(),level:"error",event:"terminalize_clean_exit_unverified_failed",agent_id:worker.id,error:message}),{terminalized:!1,executorId:null}}}async function reconcileUnresumable(deps){let workers=await deps.listWorkers(),flipped=0;for(let worker of workers){if(worker.state!=="error")continue;if(worker.autoResume===!1)continue;if(worker.currentSessionId)continue;try{await deps.updateAgent(worker.id,{autoResume:!1}),deps.log({timestamp:deps.now().toISOString(),level:"warn",event:"agent_marked_unresumable",agent_id:worker.id,reason:"no_session_id",state:worker.state}),flipped++}catch(err){let message=err instanceof Error?err.message:String(err);deps.log({timestamp:deps.now().toISOString(),level:"warn",event:"agent_marked_unresumable_failed",agent_id:worker.id,error:message})}}return flipped}async function countActiveWorkers(workers,isPaneAlive2){let count=0;for(let w of workers){if(w.state==null||INACTIVE_WORKER_STATES.has(w.state))continue;if(/^%\d+$/.test(w.paneId))try{if(!await isPaneAlive2(w.paneId))continue}catch{}count++}return count}function telemetryState(raw){return raw&&TELEMETRY_STATES.has(raw)?raw:"unknown"}function recordResumeTelemetry(eventType,payload,actor){recordAuditEvent("agent.resume",payload.entity_id,eventType,actor,payload).catch(()=>{});try{let v2Payload={entity_id:payload.entity_id,attempt_number:payload.attempt_number,state_before:payload.state_before,state_after:payload.state_after,trigger:payload.trigger};if(payload.last_error)v2Payload.last_error=payload.last_error.slice(0,500);if(eventType==="agent.resume.failed")v2Payload.exhausted=payload.exhausted??!1;emitEvent(eventType,v2Payload,{severity:eventType==="agent.resume.failed"?"warn":"info",source_subsystem:"scheduler.auto-resume"})}catch{}}async function attemptAgentResume(deps,config,agent){let now=deps.now(),agentId=agent.id;if(agent.autoResume===!1)return deps.log({timestamp:now.toISOString(),level:"debug",event:"agent_resume_skipped",agent_id:agentId,reason:"auto_resume_disabled"}),"skipped";let maxAttempts=agent.maxResumeAttempts??DEFAULT_MAX_RESUME_ATTEMPTS,attempts=agent.resumeAttempts??0;if(!agent.currentSessionId){let newAttempts2=attempts+1;await deps.updateAgent(agentId,{resumeAttempts:newAttempts2,lastResumeAttempt:now.toISOString()}),deps.log({timestamp:now.toISOString(),level:"debug",event:"agent_resume_skipped",agent_id:agentId,reason:"no_session_id",resume_attempts:newAttempts2,max_resume_attempts:maxAttempts});try{let{recordResumeMissingSession:recordResumeMissingSession2}=await Promise.resolve().then(() => (init_executor_registry(),exports_executor_registry)),actor=process.env.GENIE_AGENT_NAME??"scheduler";await recordResumeMissingSession2(agentId,actor,{reason:"no_session_id"})}catch{}if(newAttempts2>=maxAttempts)return await deps.updateAgent(agentId,{autoResume:!1}),deps.log({timestamp:now.toISOString(),level:"warn",event:"agent_resume_exhausted",agent_id:agentId,resume_attempts:newAttempts2,max_resume_attempts:maxAttempts,reason:"no_session_id_orphan"}),"exhausted";return"skipped"}if(attempts>=maxAttempts)return await deps.updateAgent(agentId,{autoResume:!1}),deps.log({timestamp:now.toISOString(),level:"warn",event:"agent_resume_exhausted",agent_id:agentId,resume_attempts:attempts,max_resume_attempts:maxAttempts}),"exhausted";if(agent.lastResumeAttempt){let lastAttempt=new Date(agent.lastResumeAttempt).getTime();if(now.getTime()-lastAttempt<RESUME_COOLDOWN_MS)return deps.log({timestamp:now.toISOString(),level:"debug",event:"agent_resume_skipped",agent_id:agentId,reason:"cooldown",last_attempt:agent.lastResumeAttempt}),"skipped"}let workers=await deps.listWorkers(),activeCount=await countActiveWorkers(workers,deps.isPaneAlive);if(activeCount>=config.maxConcurrent)return deps.log({timestamp:now.toISOString(),level:"debug",event:"agent_resume_skipped",agent_id:agentId,reason:"concurrency_cap",active:activeCount,max:config.maxConcurrent}),"skipped";let newAttempts=attempts+1;await deps.updateAgent(agentId,{resumeAttempts:newAttempts,lastResumeAttempt:now.toISOString()}),deps.log({timestamp:now.toISOString(),level:"info",event:"agent_resume_attempted",agent_id:agentId,resume_attempts:newAttempts,max_resume_attempts:maxAttempts});let stateBefore=telemetryState(agent.state);if(recordResumeTelemetry("agent.resume.attempted",{entity_id:agentId,attempt_number:newAttempts,state_before:stateBefore,state_after:stateBefore,trigger:"scheduler"},"scheduler"),await deps.resumeAgent(agentId))return await deps.updateAgent(agentId,{resumeAttempts:0}),deps.log({timestamp:now.toISOString(),level:"info",event:"agent_resume_succeeded",agent_id:agentId,resume_attempts:newAttempts}),recordResumeTelemetry("agent.resume.succeeded",{entity_id:agentId,attempt_number:newAttempts,state_before:stateBefore,state_after:"spawning",trigger:"scheduler"},"scheduler"),"resumed";deps.log({timestamp:now.toISOString(),level:"warn",event:"agent_resume_failed",agent_id:agentId,resume_attempts:newAttempts,max_resume_attempts:maxAttempts});let willExhaust=newAttempts>=maxAttempts;if(recordResumeTelemetry("agent.resume.failed",{entity_id:agentId,attempt_number:newAttempts,state_before:stateBefore,state_after:stateBefore,trigger:"scheduler",exhausted:willExhaust},"scheduler"),newAttempts>=maxAttempts)return await deps.updateAgent(agentId,{autoResume:!1}),deps.log({timestamp:now.toISOString(),level:"warn",event:"agent_resume_exhausted",agent_id:agentId,resume_attempts:newAttempts,max_resume_attempts:maxAttempts}),"exhausted";return"skipped"}async function collectHeartbeats(deps){let sql=await deps.getConnection(),now=deps.now(),activeRuns=await sql`
|
|
2212
2212
|
SELECT id, worker_id, status, trigger_id FROM runs WHERE status = 'running'
|
|
2213
2213
|
`,workers=await deps.listWorkers(),workerById=new Map(workers.map((w)=>[w.id,w])),collected=0;for(let run of activeRuns){let{alive,isPid}=await checkWorkerAlive(deps,run.worker_id),heartbeatStatus=alive?isPid?"busy":"alive":"dead",worker=workerById.get(run.worker_id),context={alive,pid_check:isPid,worker_id:run.worker_id,team:worker?.team??null,wish_slug:worker?.wishSlug??null,group_number:worker?.groupNumber??null,state:worker?.state??null},heartbeatId=deps.generateId();await sql`
|
|
2214
2214
|
INSERT INTO heartbeats (id, worker_id, run_id, status, context, last_seen_at, created_at)
|
|
@@ -2501,7 +2501,7 @@ ${queryContent}`;let{messages:queryMessages}=state.provider.runQuery({agentId:se
|
|
|
2501
2501
|
`);applyTuiStyle(),setupTuiKeybindings();try{execSync10(tuiTmux(`select-pane -t ${panes[0]}`),{stdio:"ignore"})}catch{}return{leftPane:panes[0],rightPane:panes[1]||panes[0]}}function sendTuiLaunchScript(leftPane,rightPane,workspaceRoot){let home=genieHome3(),bunPath=process.execPath||"bun",genieBin=process.argv[1]||"genie",scriptPath=join55(home,"tui-launch.sh"),logsDir=join55(home,"logs"),crashLog=join55(logsDir,"tui-crash.log"),envVars=["GENIE_TUI_PANE=left",`GENIE_TUI_RIGHT=${rightPane}`];if(workspaceRoot)envVars.push(`GENIE_TUI_WORKSPACE=${workspaceRoot}`);let content=["#!/bin/sh",`mkdir -p '${logsDir}'`,`exec 2>> '${crashLog}'`,`printf -- '--- tui-launch %s pid=%s ---\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" >&2`,`export ${envVars.join(`
|
|
2502
2502
|
export `)}`,`exec ${bunPath} ${genieBin}`,""].join(`
|
|
2503
2503
|
`);writeFileSync16(scriptPath,content,{mode:493});try{execSync10(tuiTmux(`send-keys -t '${leftPane}' '${scriptPath}' Enter`),{stdio:"ignore"})}catch{}}function killTuiSession(){try{execSync10(tuiTmux("kill-server"),{stdio:"ignore"})}catch{}}function listAgentSessions(){try{return execSync10(genieTmuxCmd("list-sessions -F '#{session_name}'"),{encoding:"utf-8"}).trim().split(`
|
|
2504
|
-
`).filter(Boolean)}catch{return[]}}function isServeRunning(){let entry2=readServePid();return entry2!==null&&isProcessAlive(entry2.pid)}async function autoStartServe(){if(isStoppingLockActive()){console.log("genie serve is shutting down \u2014 skipping auto-start.");return}if(isServeRunning())return;let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie",{spawn:spawnChild}=await import("child_process");spawnChild(bunPath,[genieBin,"serve","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref();let deadline=Date.now()+15000;while(Date.now()<deadline)if(await new Promise((resolve10)=>setTimeout(resolve10,500)),isServeRunning()&&isTuiSessionReady())return;if(!isServeRunning())throw Error("genie serve failed to start within 15s. Run `genie serve` manually.")}function isTuiSessionReady(){try{return execSync10(tuiTmux(`has-session -t ${TUI_SESSION}`),{stdio:"ignore"}),!0}catch{return!1}}function ensureTuiSession(workspaceRoot){if(isTuiDisabled()){noticeTuiSkipped("session ensure");return}if(isTuiSessionReady())return;let{leftPane,rightPane}=startTuiTmuxServer();sendTuiLaunchScript(leftPane,rightPane,workspaceRoot)}async function startAgentSync(){try{let{findWorkspace:findWorkspace2,genieHome:genieHome4}=(init_workspace(),__toCommonJS(exports_workspace)),ws=findWorkspace2();if(!ws){let{join:join56}=__require("path"),configPath2=join56(genieHome4(),"config.json");return console.warn(` Agent sync: DISABLED \u2014 no workspace found from cwd or ${configPath2}`),console.warn(" Fix: `cd <workspace> && genie serve restart`, or run `genie init` to bootstrap one"),null}let{syncAgentDirectory:syncAgentDirectory2,watchAgentDirectory:watchAgentDirectory2}=await Promise.resolve().then(() => (init_agent_sync(),exports_agent_sync)),syncResult=await syncAgentDirectory2(ws.root);if(syncResult.registered.length+syncResult.updated.length>0)console.log(` Agent sync: ${syncResult.registered.length} registered, ${syncResult.updated.length} updated (workspace: ${ws.root})`);else console.log(` Agent sync: up to date (workspace: ${ws.root})`);if(syncResult.errors.length>0){console.warn(` Agent sync: ${syncResult.errors.length} error(s) \u2014 these agents were NOT registered:`);for(let e of syncResult.errors)console.warn(` ${e.name}: ${e.error}`)}let watcher2=watchAgentDirectory2(ws.root,{onSync:(name,action)=>{console.log(` [agent-watcher] ${name}: ${action}`)}});if(watcher2)console.log(" Agent watcher started (watching agents/ directory)");else console.warn(" Agent watcher: FAILED to start \u2014 new agents will not be auto-registered");return watcher2}catch(err){let msg=err instanceof Error?err.message:String(err);return console.error(` Agent sync failed: ${msg}`),null}}async function startPgserve(){console.log(" Starting pgserve...");try{let{ensurePgserve:ensurePgserve2}=await Promise.resolve().then(() => (init_db(),exports_db)),port=await ensurePgserve2();console.log(` pgserve ready on port ${port}`);try{let{registerService:registerService2}=await Promise.resolve().then(() => (init_service_registry(),exports_service_registry));registerService2("pgserve-owner",process.pid)}catch{}}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` pgserve failed: ${msg}`)}}async function startScheduler(){console.log(" Starting scheduler daemon...");try{let{startDaemon:startDaemon2}=await Promise.resolve().then(() => (init_scheduler_daemon(),exports_scheduler_daemon));handles.schedulerHandle=startDaemon2(),console.log(" Scheduler started (includes event-router + inbox-watcher)");try{let{registerService:registerService2}=await Promise.resolve().then(() => (init_service_registry(),exports_service_registry));registerService2("scheduler",process.pid)}catch{}}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` Scheduler failed: ${msg}`)}try{let{startDerivedSignalsEngine:startDerivedSignalsEngine2}=await Promise.resolve().then(() => (init_derived_signals(),exports_derived_signals));handles.derivedSignals=await startDerivedSignalsEngine2(),console.log(" Derived-signal rule engine subscribed")}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` Derived-signal engine failed: ${msg}`)}}function claimServePidOrExit(){let path3=servePidPath();mkdirSync18(genieHome3(),{recursive:!0});let startTime=getProcessStartTime(process.pid)??"unknown",payload=`${process.pid}:${startTime}`;for(let attempt=0;attempt<2;attempt++)try{let fd=openSync5(path3,"wx",420);try{writeSync2(fd,payload)}finally{closeSync5(fd)}return}catch(err){if(err.code!=="EEXIST")throw err;let existing=readServePid();if(existing&&existing.startTime!==null&&isProcessAlive(existing.pid))console.log(`genie serve already running (PID ${existing.pid})`),warnIfHookSocketMissing(),process.exit(0);forceRemoveServePid()}console.error("Could not claim serve.pid after 2 attempts \u2014 another genie serve is racing this one. "+"Wait a moment and retry, or run `genie serve status`."),process.exit(1)}function resolveServeMode(headless){let tuiDisabled=isTuiDisabled();if(tuiDisabled&&!headless)noticeTuiSkipped("serve");return{skipTui:Boolean(headless)||tuiDisabled,mode:headless?"headless":tuiDisabled?"no-tui":"full"}}async function loadBrainStartupConfig(deps){return deps.loadConfig?.()??(await Promise.resolve().then(() => (init_genie_config2(),exports_genie_config))).loadGenieConfigSync()}async function importBrainForStartup(deps){if(deps.importBrain)return deps.importBrain();return import("@khal-os/brain")}async function getBrainStartupPgPort(deps){return deps.getActivePort?.()??(await Promise.resolve().then(() => (init_db(),exports_db))).getActivePort()}function assignBrainHandles(deps,brainHandles){if(deps.setBrainHandles){deps.setBrainHandles(brainHandles);return}handles.brainHandles=brainHandles}function isMissingBrainModule(message){return message.includes("Cannot find")||message.includes("not found")||message.includes("MODULE_NOT_FOUND")}async function startBrainServer(deps,config,log2,warn){let brain=await importBrainForStartup(deps);if(!brain.startEmbeddedBrainServer)return[];let pgPort=await getBrainStartupPgPort(deps);if(!pgPort)return log2(" Brain server: pgserve not available (skipped)"),[];let resolveVaults=deps.resolveVaults??resolveBrainVaults,startVaults=deps.startVaults??startResolvedBrainVaults,resolution=await resolveVaults({brain,config,warn});if(resolution.paths.length===0)return log2(` Brain server: no ${resolution.source} brain vaults found (skipped)`),[];log2(` Starting brain server (${resolution.paths.length} ${resolution.source} vault(s))...`);let brainHandles=await startVaults(resolution,brain,pgPort,{warn,log:log2});if(assignBrainHandles(deps,brainHandles),brainHandles.length===0)log2(" Brain server: no vaults started");return brainHandles}async function startBrainServerIfEnabled(deps={}){let config=await loadBrainStartupConfig(deps),brainEmbedded=config.brain?.embedded!==!1,log2=deps.log??console.log,warn=deps.warn??console.warn;if(!brainEmbedded)return log2(" Brain server: skipped (brain.embedded=false \u2014 managed externally)"),[];try{return await startBrainServer(deps,config,log2,warn)}catch(err){let msg=err instanceof Error?err.message:String(err);if(isMissingBrainModule(msg))return[];return warn(` Brain server: failed: ${msg}`),[]}}function logAgentSessionInfo(){let sessions=listAgentSessions();if(sessions.length>0)console.log(` Agent server (-L genie): ${sessions.length} sessions`);else console.log(" Agent server (-L genie): no sessions yet (created on first spawn)")}function startTuiSessionIfEnabled(skipTui){if(skipTui)return;console.log(" Setting up TUI session...");let{leftPane,rightPane}=startTuiTmuxServer(),ws=(()=>{try{let{findWorkspace:findWorkspace2}=(init_workspace(),__toCommonJS(exports_workspace));return findWorkspace2()}catch{return null}})();sendTuiLaunchScript(leftPane,rightPane,ws?.root),console.log(" TUI server ready (session: genie-tui)")}async function startDetectorSchedulerSafely(){try{await Promise.resolve().then(() => (init_built_in(),exports_built_in));let{start:startDetectorScheduler}=await Promise.resolve().then(() => (init_detector_scheduler(),exports_detector_scheduler)),{listDetectors:listDetectors2}=await Promise.resolve().then(() => (init_detectors(),exports_detectors));handles.detectorScheduler=startDetectorScheduler();let registered=listDetectors2().map((d)=>d.id);console.log(` Detector scheduler started (measurement only, 60s \xB1 5s cadence) \u2014 registered: [${registered.join(", ")}]`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.warn(` Detector scheduler: failed \u2014 ${msg}`)}}async function startExecutorReadEndpointSafely(){try{let{startExecutorReadEndpoint:startExecutorReadEndpoint2,getExecutorReadPort:getExecutorReadPort2}=await Promise.resolve().then(() => (init_executor_read(),exports_executor_read));if(await startExecutorReadEndpoint2())console.log(` Executor read endpoint ready on port ${getExecutorReadPort2()}`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.warn(` Executor read endpoint: failed \u2014 ${msg}`)}}async function startOmniApprovalHandlerSafely(){try{let{startOmniApprovalHandler:startOmniApprovalHandler2}=await Promise.resolve().then(() => (init_omni_approval_handler(),exports_omni_approval_handler)),handler=await startOmniApprovalHandler2();if(handler)handles.omniApprovalHandler=handler,console.log(" Omni approval handler started")}catch{}}async function startOmniBridgeSafely(){let{OmniBridge:OmniBridge2}=await Promise.resolve().then(() => (init_omni_bridge(),exports_omni_bridge)),bridge=new OmniBridge2({natsUrl:process.env.GENIE_NATS_URL??"localhost:4222",maxConcurrent:Number(process.env.GENIE_MAX_CONCURRENT??"20"),idleTimeoutMs:Number(process.env.GENIE_IDLE_TIMEOUT_MS??"900000")});try{await bridge.start(),handles.omniBridge=bridge,console.log(" Omni bridge started")}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.GENIE_OMNI_REQUIRED==="1")console.error(` Omni bridge: FAILED \u2014 ${msg}`),process.exit(1);console.warn(` Omni bridge: degraded \u2014 ${msg}; set GENIE_OMNI_REQUIRED=1 to make this fatal`)}}async function stopSchedulerHandles(){handles.agentWatcher?.close();let schedulerHandle=handles.schedulerHandle;if(schedulerHandle){schedulerHandle.stop();try{await schedulerHandle.done}catch{}handles.schedulerHandle=null}if(handles.detectorScheduler)handles.detectorScheduler.stop(),handles.detectorScheduler=null;if(handles.derivedSignals)await handles.derivedSignals.stop().catch(()=>{}),handles.derivedSignals=null}async function stopOmniAndBrainServices(){if(handles.omniApprovalHandler)await handles.omniApprovalHandler.stop().catch(()=>{}),handles.omniApprovalHandler=null;if(handles.omniBridge)await handles.omniBridge.stop().catch(()=>{}),handles.omniBridge=null;if(Promise.resolve().then(() => (init_executor_read(),exports_executor_read)).then((m)=>m.stopExecutorReadEndpoint().catch(()=>{})),handles.brainHandles.length>0){for(let handle of handles.brainHandles)await handle.stop().catch(()=>{});handles.brainHandles=[]}}function killRegisteredServices(){try{let{killAllServices:killAllServices2}=(init_service_registry(),__toCommonJS(exports_service_registry));killAllServices2()}catch{}}function removePgservePortLockfile(){try{let lockfilePath=join55(genieHome3(),"pgserve.port");if(existsSync44(lockfilePath))unlinkSync11(lockfilePath)}catch{}}function sigKillRegisteredServices(){try{let{getRegisteredServices:getRegisteredServices2}=(init_service_registry(),__toCommonJS(exports_service_registry));for(let svc of getRegisteredServices2())try{process.kill(svc.pid,"SIGKILL")}catch{}}catch{}}async function startHookSocketSafely(){try{let{startHookSocket:startHookSocket2}=await Promise.resolve().then(() => (init_hook_socket(),exports_hook_socket));handles.hookSocket=await startHookSocket2()}catch(err){console.warn(` Hook socket: DISABLED \u2014 ${err.message}`),handles.hookSocket=null}}async function stopHookSocketSafely(){if(!handles.hookSocket)return;try{await handles.hookSocket.stop()}catch{}handles.hookSocket=null}function buildShutdownFn(headless){let shutdownStarted=!1;return{shutdown:async()=>{if(shutdownStarted)return;if(shutdownStarted=!0,console.log(`
|
|
2504
|
+
`).filter(Boolean)}catch{return[]}}function isServeRunning(){let entry2=readServePid();return entry2!==null&&isProcessAlive(entry2.pid)}async function autoStartServe(){if(isStoppingLockActive()){console.log("genie serve is shutting down \u2014 skipping auto-start.");return}if(isServeRunning())return;let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie",{spawn:spawnChild}=await import("child_process");spawnChild(bunPath,[genieBin,"serve","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref();let deadline=Date.now()+15000;while(Date.now()<deadline)if(await new Promise((resolve10)=>setTimeout(resolve10,500)),isServeRunning()&&isTuiSessionReady())return;if(!isServeRunning())throw Error("genie serve failed to start within 15s. Run `genie serve` manually.")}function isTuiSessionReady(){try{return execSync10(tuiTmux(`has-session -t ${TUI_SESSION}`),{stdio:"ignore"}),!0}catch{return!1}}function ensureTuiSession(workspaceRoot){if(isTuiDisabled()){noticeTuiSkipped("session ensure");return}if(isTuiSessionReady())return;let{leftPane,rightPane}=startTuiTmuxServer();sendTuiLaunchScript(leftPane,rightPane,workspaceRoot)}async function startAgentSync(){try{let{findWorkspace:findWorkspace2,genieHome:genieHome4}=(init_workspace(),__toCommonJS(exports_workspace)),ws=findWorkspace2();if(!ws){let{join:join56}=__require("path"),configPath2=join56(genieHome4(),"config.json");return console.warn(` Agent sync: DISABLED \u2014 no workspace found from cwd or ${configPath2}`),console.warn(" Fix: `cd <workspace> && genie serve restart`, or run `genie init` to bootstrap one"),null}let{syncAgentDirectory:syncAgentDirectory2,watchAgentDirectory:watchAgentDirectory2}=await Promise.resolve().then(() => (init_agent_sync(),exports_agent_sync)),syncResult=await syncAgentDirectory2(ws.root);if(syncResult.registered.length+syncResult.updated.length>0)console.log(` Agent sync: ${syncResult.registered.length} registered, ${syncResult.updated.length} updated (workspace: ${ws.root})`);else console.log(` Agent sync: up to date (workspace: ${ws.root})`);if(syncResult.errors.length>0){console.warn(` Agent sync: ${syncResult.errors.length} error(s) \u2014 these agents were NOT registered:`);for(let e of syncResult.errors)console.warn(` ${e.name}: ${e.error}`)}let watcher2=watchAgentDirectory2(ws.root,{onSync:(name,action)=>{console.log(` [agent-watcher] ${name}: ${action}`)}});if(watcher2)console.log(" Agent watcher started (watching agents/ directory)");else console.warn(" Agent watcher: FAILED to start \u2014 new agents will not be auto-registered");return watcher2}catch(err){let msg=err instanceof Error?err.message:String(err);return console.error(` Agent sync failed: ${msg}`),null}}async function startPgserve(){console.log(" Starting pgserve...");try{let{ensurePgserve:ensurePgserve2}=await Promise.resolve().then(() => (init_db(),exports_db)),port=await ensurePgserve2();console.log(` pgserve ready on port ${port}`);try{let{registerService:registerService2}=await Promise.resolve().then(() => (init_service_registry(),exports_service_registry));registerService2("pgserve-owner",process.pid)}catch{}}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` pgserve failed: ${msg}`),process.env.GENIE_PG_NO_AUTOSTART="1",console.error(" pgserve retries disabled for this serve process; fix pgserve and restart `genie serve`.")}}async function startScheduler(){console.log(" Starting scheduler daemon...");try{let{startDaemon:startDaemon2}=await Promise.resolve().then(() => (init_scheduler_daemon(),exports_scheduler_daemon));handles.schedulerHandle=startDaemon2(),console.log(" Scheduler started (includes event-router + inbox-watcher)");try{let{registerService:registerService2}=await Promise.resolve().then(() => (init_service_registry(),exports_service_registry));registerService2("scheduler",process.pid)}catch{}}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` Scheduler failed: ${msg}`)}try{let{startDerivedSignalsEngine:startDerivedSignalsEngine2}=await Promise.resolve().then(() => (init_derived_signals(),exports_derived_signals));handles.derivedSignals=await startDerivedSignalsEngine2(),console.log(" Derived-signal rule engine subscribed")}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` Derived-signal engine failed: ${msg}`)}}function claimServePidOrExit(){let path3=servePidPath();mkdirSync18(genieHome3(),{recursive:!0});let startTime=getProcessStartTime(process.pid)??"unknown",payload=`${process.pid}:${startTime}`;for(let attempt=0;attempt<2;attempt++)try{let fd=openSync5(path3,"wx",420);try{writeSync2(fd,payload)}finally{closeSync5(fd)}return}catch(err){if(err.code!=="EEXIST")throw err;let existing=readServePid();if(existing&&existing.startTime!==null&&isProcessAlive(existing.pid))console.log(`genie serve already running (PID ${existing.pid})`),warnIfHookSocketMissing(),process.exit(0);forceRemoveServePid()}console.error("Could not claim serve.pid after 2 attempts \u2014 another genie serve is racing this one. "+"Wait a moment and retry, or run `genie serve status`."),process.exit(1)}function resolveServeMode(headless){let tuiDisabled=isTuiDisabled();if(tuiDisabled&&!headless)noticeTuiSkipped("serve");return{skipTui:Boolean(headless)||tuiDisabled,mode:headless?"headless":tuiDisabled?"no-tui":"full"}}async function loadBrainStartupConfig(deps){return deps.loadConfig?.()??(await Promise.resolve().then(() => (init_genie_config2(),exports_genie_config))).loadGenieConfigSync()}async function importBrainForStartup(deps){if(deps.importBrain)return deps.importBrain();return import("@khal-os/brain")}async function getBrainStartupPgPort(deps){return deps.getActivePort?.()??(await Promise.resolve().then(() => (init_db(),exports_db))).getActivePort()}function assignBrainHandles(deps,brainHandles){if(deps.setBrainHandles){deps.setBrainHandles(brainHandles);return}handles.brainHandles=brainHandles}function isMissingBrainModule(message){return message.includes("Cannot find")||message.includes("not found")||message.includes("MODULE_NOT_FOUND")}async function startBrainServer(deps,config,log2,warn){let brain=await importBrainForStartup(deps);if(!brain.startEmbeddedBrainServer)return[];let pgPort=await getBrainStartupPgPort(deps);if(!pgPort)return log2(" Brain server: pgserve not available (skipped)"),[];let resolveVaults=deps.resolveVaults??resolveBrainVaults,startVaults=deps.startVaults??startResolvedBrainVaults,resolution=await resolveVaults({brain,config,warn});if(resolution.paths.length===0)return log2(` Brain server: no ${resolution.source} brain vaults found (skipped)`),[];log2(` Starting brain server (${resolution.paths.length} ${resolution.source} vault(s))...`);let brainHandles=await startVaults(resolution,brain,pgPort,{warn,log:log2});if(assignBrainHandles(deps,brainHandles),brainHandles.length===0)log2(" Brain server: no vaults started");return brainHandles}async function startBrainServerIfEnabled(deps={}){let config=await loadBrainStartupConfig(deps),brainEmbedded=config.brain?.embedded!==!1,log2=deps.log??console.log,warn=deps.warn??console.warn;if(!brainEmbedded)return log2(" Brain server: skipped (brain.embedded=false \u2014 managed externally)"),[];try{return await startBrainServer(deps,config,log2,warn)}catch(err){let msg=err instanceof Error?err.message:String(err);if(isMissingBrainModule(msg))return[];return warn(` Brain server: failed: ${msg}`),[]}}function logAgentSessionInfo(){let sessions=listAgentSessions();if(sessions.length>0)console.log(` Agent server (-L genie): ${sessions.length} sessions`);else console.log(" Agent server (-L genie): no sessions yet (created on first spawn)")}function startTuiSessionIfEnabled(skipTui){if(skipTui)return;console.log(" Setting up TUI session...");let{leftPane,rightPane}=startTuiTmuxServer(),ws=(()=>{try{let{findWorkspace:findWorkspace2}=(init_workspace(),__toCommonJS(exports_workspace));return findWorkspace2()}catch{return null}})();sendTuiLaunchScript(leftPane,rightPane,ws?.root),console.log(" TUI server ready (session: genie-tui)")}async function startDetectorSchedulerSafely(){try{await Promise.resolve().then(() => (init_built_in(),exports_built_in));let{start:startDetectorScheduler}=await Promise.resolve().then(() => (init_detector_scheduler(),exports_detector_scheduler)),{listDetectors:listDetectors2}=await Promise.resolve().then(() => (init_detectors(),exports_detectors));handles.detectorScheduler=startDetectorScheduler();let registered=listDetectors2().map((d)=>d.id);console.log(` Detector scheduler started (measurement only, 60s \xB1 5s cadence) \u2014 registered: [${registered.join(", ")}]`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.warn(` Detector scheduler: failed \u2014 ${msg}`)}}async function startExecutorReadEndpointSafely(){try{let{startExecutorReadEndpoint:startExecutorReadEndpoint2,getExecutorReadPort:getExecutorReadPort2}=await Promise.resolve().then(() => (init_executor_read(),exports_executor_read));if(await startExecutorReadEndpoint2())console.log(` Executor read endpoint ready on port ${getExecutorReadPort2()}`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.warn(` Executor read endpoint: failed \u2014 ${msg}`)}}async function startOmniApprovalHandlerSafely(){try{let{startOmniApprovalHandler:startOmniApprovalHandler2}=await Promise.resolve().then(() => (init_omni_approval_handler(),exports_omni_approval_handler)),handler=await startOmniApprovalHandler2();if(handler)handles.omniApprovalHandler=handler,console.log(" Omni approval handler started")}catch{}}async function startOmniBridgeSafely(){let{OmniBridge:OmniBridge2}=await Promise.resolve().then(() => (init_omni_bridge(),exports_omni_bridge)),bridge=new OmniBridge2({natsUrl:process.env.GENIE_NATS_URL??"localhost:4222",maxConcurrent:Number(process.env.GENIE_MAX_CONCURRENT??"20"),idleTimeoutMs:Number(process.env.GENIE_IDLE_TIMEOUT_MS??"900000")});try{await bridge.start(),handles.omniBridge=bridge,console.log(" Omni bridge started")}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.GENIE_OMNI_REQUIRED==="1")console.error(` Omni bridge: FAILED \u2014 ${msg}`),process.exit(1);console.warn(` Omni bridge: degraded \u2014 ${msg}; set GENIE_OMNI_REQUIRED=1 to make this fatal`)}}async function stopSchedulerHandles(){handles.agentWatcher?.close();let schedulerHandle=handles.schedulerHandle;if(schedulerHandle){schedulerHandle.stop();try{await schedulerHandle.done}catch{}handles.schedulerHandle=null}if(handles.detectorScheduler)handles.detectorScheduler.stop(),handles.detectorScheduler=null;if(handles.derivedSignals)await handles.derivedSignals.stop().catch(()=>{}),handles.derivedSignals=null}async function stopOmniAndBrainServices(){if(handles.omniApprovalHandler)await handles.omniApprovalHandler.stop().catch(()=>{}),handles.omniApprovalHandler=null;if(handles.omniBridge)await handles.omniBridge.stop().catch(()=>{}),handles.omniBridge=null;if(Promise.resolve().then(() => (init_executor_read(),exports_executor_read)).then((m)=>m.stopExecutorReadEndpoint().catch(()=>{})),handles.brainHandles.length>0){for(let handle of handles.brainHandles)await handle.stop().catch(()=>{});handles.brainHandles=[]}}function killRegisteredServices(){try{let{killAllServices:killAllServices2}=(init_service_registry(),__toCommonJS(exports_service_registry));killAllServices2()}catch{}}function removePgservePortLockfile(){try{let lockfilePath=join55(genieHome3(),"pgserve.port");if(existsSync44(lockfilePath))unlinkSync11(lockfilePath)}catch{}}function sigKillRegisteredServices(){try{let{getRegisteredServices:getRegisteredServices2}=(init_service_registry(),__toCommonJS(exports_service_registry));for(let svc of getRegisteredServices2())try{process.kill(svc.pid,"SIGKILL")}catch{}}catch{}}async function startHookSocketSafely(){try{let{startHookSocket:startHookSocket2}=await Promise.resolve().then(() => (init_hook_socket(),exports_hook_socket));handles.hookSocket=await startHookSocket2()}catch(err){console.warn(` Hook socket: DISABLED \u2014 ${err.message}`),handles.hookSocket=null}}async function stopHookSocketSafely(){if(!handles.hookSocket)return;try{await handles.hookSocket.stop()}catch{}handles.hookSocket=null}function buildShutdownFn(headless){let shutdownStarted=!1;return{shutdown:async()=>{if(shutdownStarted)return;if(shutdownStarted=!0,console.log(`
|
|
2505
2505
|
Shutting down genie serve...`),await stopHookSocketSafely(),await stopSchedulerHandles(),await stopOmniAndBrainServices(),killRegisteredServices(),!headless)killTuiSession();removePgservePortLockfile(),removeServePid(),console.log("genie serve stopped.")},hasStarted:()=>shutdownStarted}}function installGracefulExitHandlers(shutdown2,hasStarted){let gracefulExit=(exitCode)=>{if(hasStarted())return;let forceTimer=setTimeout(()=>{console.error("Graceful shutdown timeout (10s). Force-killing remaining processes."),sigKillRegisteredServices(),removeServePid(),process.exit(1)},1e4);forceTimer.unref(),shutdown2().catch(()=>{}).finally(()=>{clearTimeout(forceTimer),removeServePid(),process.exit(exitCode)})};process.on("SIGTERM",()=>gracefulExit(143)),process.on("SIGINT",()=>gracefulExit(130)),process.on("SIGHUP",()=>gracefulExit(129)),process.on("exit",()=>{removeServePid()}),process.on("uncaughtException",(err)=>{console.error("Uncaught exception in genie serve:",err),gracefulExit(1)})}function writeStartupStatus(status){let statusPath=process.env.GENIE_SERVE_STARTUP_STATUS;if(!statusPath)return;try{mkdirSync18(dirname14(statusPath),{recursive:!0}),writeFileSync16(statusPath,`${JSON.stringify(status)}
|
|
2506
2506
|
`,"utf-8")}catch{}}function readStartupStatus(statusPath){try{let parsed=JSON.parse(readFileSync26(statusPath,"utf-8"));if(typeof parsed.ok!=="boolean")return null;return{ok:parsed.ok,code:typeof parsed.code==="number"?parsed.code:void 0,lines:Array.isArray(parsed.lines)?parsed.lines.filter((line)=>typeof line==="string"):void 0}}catch{return null}}async function waitForStartupStatus(statusPath,childPid,timeoutMs){let deadline=Date.now()+timeoutMs;while(Date.now()<deadline){let status=readStartupStatus(statusPath);if(status)return status;if(!isProcessAlive(childPid))return{ok:!1,code:1};await new Promise((resolve10)=>setTimeout(resolve10,100))}return null}function exitBackgroundStartFailed(){console.error("Error: genie serve exited immediately."),process.exit(1)}function exitStartupStatusFailure(status){for(let line of status.lines??[])console.error(line);process.exit(status.code??1)}function exitStartupStatusMissing(childPid){console.error("Error: genie serve did not report startup precondition status within 16s.");try{process.kill(childPid,"SIGTERM")}catch{}process.exit(1)}async function confirmBackgroundStarted(childPid,startupStatusPath){if(startupStatusPath){let status=await waitForStartupStatus(startupStatusPath,childPid,16000);if(forceRemovePath(startupStatusPath),status?.ok===!1)exitStartupStatusFailure(status);if(status?.ok!==!0)exitStartupStatusMissing(childPid);if(!isProcessAlive(childPid))exitBackgroundStartFailed();console.log(`genie serve started (PID ${childPid})`);return}if(await new Promise((resolve10)=>setTimeout(resolve10,1000)),!isProcessAlive(childPid))exitBackgroundStartFailed();console.log(`genie serve started (PID ${childPid})`)}async function startForeground(headless,autoFix=!0){claimServePidOrExit(),removePgservePortLockfile();let{skipTui,mode}=resolveServeMode(headless);process.env.GENIE_IS_DAEMON="1",console.log(`genie serve starting (PID ${process.pid}, mode: ${mode})`);let preconditionLines=[],preconditionLog=process.env.GENIE_SERVE_STARTUP_STATUS?(line)=>{preconditionLines.push(line),console.log(line)}:void 0;try{if(!await runStartPreconditions(autoFix,preconditionLog))writeStartupStatus({ok:!1,code:2,lines:preconditionLines}),removeServePid(),process.exit(2)}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(`genie serve start preconditions failed: ${msg}`),writeStartupStatus({ok:!1,code:1,lines:[...preconditionLines,`genie serve start preconditions failed: ${msg}`]}),removeServePid(),process.exit(1)}if(writeStartupStatus({ok:!0}),!skipTui)await ensureTmux();if(await startPgserve(),await startBrainServerIfEnabled(),!headless)logAgentSessionInfo();handles.agentWatcher=await startAgentSync(),startTuiSessionIfEnabled(skipTui),await startScheduler(),await startDetectorSchedulerSafely(),await startExecutorReadEndpointSafely(),await startOmniApprovalHandlerSafely(),await startOmniBridgeSafely(),await startHookSocketSafely(),console.log(`
|
|
2507
2507
|
genie serve is running (${mode}). ${headless?"Send SIGTERM to stop.":"Press Ctrl+C to stop."}`);let{shutdown:shutdown2,hasStarted}=buildShutdownFn(headless);if(installGracefulExitHandlers(shutdown2,hasStarted),handles.schedulerHandle)await handles.schedulerHandle.done;else await new Promise(()=>{});removeServePid()}async function startBackground(headless,autoFix=!0){let existingEntry=readServePid();if(existingEntry&&isProcessAlive(existingEntry.pid))console.log(`genie serve already running (PID ${existingEntry.pid})`),process.exit(0);if(existingEntry)forceRemoveServePid();let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie",startupStatusPath=autoFix?void 0:serveStartupStatusPath(),args=[genieBin,"serve","--foreground"];if(headless)args.push("--headless");if(!autoFix)args.push("--no-fix");let child=spawn4(bunPath,args,{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1",...startupStatusPath?{GENIE_SERVE_STARTUP_STATUS:startupStatusPath}:{}}});if(child.unref(),child.pid)await confirmBackgroundStarted(child.pid,startupStatusPath);else console.error("Error: failed to spawn genie serve"),process.exit(1)}function forceRemoveServePid(){forceRemovePath(servePidPath())}function forceRemovePath(path3){try{unlinkSync11(path3)}catch{}}async function stopServe(){let entry2=readServePid();if(!entry2){console.log("genie serve is not running (no PID file).");return}writeStoppingLockSync();try{let pid=entry2.pid;if(!isProcessAlive(pid)){console.log(`Stale PID file (PID ${pid} not running). Cleaning up.`),forceRemoveServePid(),killTuiSession();return}console.log(`Stopping genie serve (PID ${pid})...`);try{process.kill(-pid,"SIGTERM")}catch{try{process.kill(pid,"SIGTERM")}catch{}}let deadline=Date.now()+1e4;while(Date.now()<deadline&&isProcessAlive(pid))await new Promise((resolve10)=>setTimeout(resolve10,250));if(isProcessAlive(pid)){console.log("Did not stop within 10s. Sending SIGKILL.");try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}killTuiSession(),forceRemoveServePid(),console.log("genie serve stopped.")}finally{clearStoppingLock()}}async function printPgserveHealth(){try{let{isAvailable:isAvailable2,getActivePort:getActivePort2}=await Promise.resolve().then(() => (init_db(),exports_db)),dbOk=await isAvailable2();console.log(` pgserve: ${dbOk?`healthy (port ${getActivePort2()})`:"unreachable"}`)}catch{console.log(" pgserve: unavailable")}}function hookSocketPath(){return process.env.GENIE_HOOK_SOCK??join55(genieHome3(),"hook.sock")}function warnIfHookSocketMissing(){let sock=hookSocketPath();if(existsSync44(sock))return;let lines=[` WARNING: hook UDS not found at ${sock}.`," Daemon-mode hook dispatch is INACTIVE \u2014 every hook will fall back"," to the legacy F1 bun-fork path (hookify-perf-foundation gains lost)."," Remediation: `genie serve stop && genie serve start` to refresh the"," daemon and re-create the socket."];console.warn(lines.join(`
|
|
@@ -3855,7 +3855,7 @@ Bus `);for(let i2=1;i2<parts.length;i2++){let usb2=parseLinuxUsb(parts[i2]);resu
|
|
|
3855
3855
|
`,lastBannerIndex);if(afterBannerNewline<0)return"";return text.slice(afterBannerNewline+1).trim()}catch{return""}finally{if(fd!==null)try{closeSync6(fd)}catch{}}}async function ingestPreviousRunCrash(logPath){let body=extractPreviousRunCrashOutput(logPath);if(!body)return;let truncated=body.length>TUI_CRASH_LOG_RECOVERY_MAX_MSG_CHARS?`${body.slice(0,TUI_CRASH_LOG_RECOVERY_MAX_MSG_CHARS)}
|
|
3856
3856
|
\u2026[truncated]`:body;try{let{emitEvent:emitEvent2}=await Promise.resolve().then(() => (init_emit(),exports_emit));emitEvent2("error.raised",{error_class:"TuiCrash",message:truncated,subsystem:"tui",severity:"error",retryable:!0})}catch{}}async function recordTuiLaunchBreadcrumb(){try{let logsDir=join83(genieHome6(),"logs");mkdirSync28(logsDir,{recursive:!0});let logPath=join83(logsDir,"tui-crash.log");await ingestPreviousRunCrash(logPath);let ts3=new Date().toISOString(),line=`${TUI_CRASH_LOG_BANNER_PREFIX}${ts3} pid=${process.pid} platform=${process.platform} arch=${process.arch} ---
|
|
3857
3857
|
`;appendFileSync4(logPath,line,{mode:420})}catch{}}async function launchTui(){await recordTuiLaunchBreadcrumb();let{renderNav:renderNav2}=await init_render().then(() => exports_render);await renderNav2()}var TUI_CRASH_LOG_BANNER_PREFIX="--- tui-launch ",TUI_CRASH_LOG_RECOVERY_MAX_BYTES=65536,TUI_CRASH_LOG_RECOVERY_MAX_MSG_CHARS=3000;var init_tui=()=>{};var exports_resolve_agent_cwd={};__export(exports_resolve_agent_cwd,{resolveAgentFromCwd:()=>resolveAgentFromCwd});import{existsSync as existsSync67}from"fs";import{basename as basename16,dirname as dirname25,join as join84,relative as relative10,sep as sep3}from"path";function isRelativeWithin(rel,original){return!rel.startsWith("..")&&rel!==original}function resolveFromCanonicalDir(cwd,agentsDir){let relToAgents=relative10(agentsDir,cwd);if(!isRelativeWithin(relToAgents,cwd))return null;let segments=relToAgents.split(sep3).filter(Boolean);if(segments.length===0)return null;let agentName=segments[0];if(!existsSync67(join84(agentsDir,agentName,"AGENTS.md")))return null;let source=segments.length===1?"exact":"parent";return{agent:agentName,source}}function resolveFromWalkUp(cwd,workspaceRoot){let wsRel=relative10(workspaceRoot,cwd);if(!isRelativeWithin(wsRel,cwd))return null;let current=cwd;while(current!==workspaceRoot&¤t!==dirname25(current)){if(existsSync67(join84(current,"AGENTS.md")))return{agent:basename16(current),source:"parent"};current=dirname25(current)}return null}function resolveAgentFromCwd(cwd,workspaceRoot){return resolveFromCanonicalDir(cwd,join84(workspaceRoot,"agents"))??resolveFromWalkUp(cwd,workspaceRoot)??{agent:"genie",source:"default"}}var init_resolve_agent_cwd=()=>{};var import__=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import__.default;init_doctor();init_setup();init_shortcuts();import{existsSync as existsSync23}from"fs";import{homedir as homedir24}from"os";import{join as join29}from"path";async function shortcutsShowCommand(){displayShortcuts();let home=homedir24(),tmuxConf=join29(home,".tmux.conf"),zshrc=join29(home,".zshrc"),bashrc=join29(home,".bashrc");if(console.log("Installation status:"),isShortcutsInstalled(tmuxConf))console.log(" \x1B[32m\u2713\x1B[0m tmux.conf");else console.log(" \x1B[33m-\x1B[0m tmux.conf");let shellRc=existsSync23(zshrc)?zshrc:bashrc;if(isShortcutsInstalled(shellRc))console.log(` \x1B[32m\u2713\x1B[0m ${shellRc.replace(home,"~")}`);else console.log(` \x1B[33m-\x1B[0m ${shellRc.replace(home,"~")}`);console.log(),console.log("Run \x1B[36mgenie shortcuts install\x1B[0m to install shortcuts."),console.log("Run \x1B[36mgenie shortcuts uninstall\x1B[0m to remove shortcuts."),console.log()}async function shortcutsInstallCommand(){await installShortcuts()}async function shortcutsUninstallCommand(){await uninstallShortcuts()}init_esm14();init_claude_settings();init_genie_config2();import{existsSync as existsSync24,lstatSync,rmSync as rmSync2,unlinkSync as unlinkSync8}from"fs";import{homedir as homedir25}from"os";import{join as join30}from"path";var ORCHESTRATION_RULES_PATH=join30(homedir25(),".claude","rules","genie-orchestration.md"),LOCAL_BIN=join30(homedir25(),".local","bin"),SYMLINKS=["genie","term"];function isGenieSymlink(path3){try{if(!existsSync24(path3))return!1;if(!lstatSync(path3).isSymbolicLink())return!1;return!0}catch{return!1}}function removeSymlinks(){let removed=[];for(let name of SYMLINKS){let symlinkPath=join30(LOCAL_BIN,name);if(isGenieSymlink(symlinkPath))try{unlinkSync8(symlinkPath),removed.push(name)}catch{}}return removed}function tryRemoveStep(label,successMsg,fn){console.log(`\x1B[2m${label}\x1B[0m`);try{fn(),console.log(` \x1B[32m+\x1B[0m ${successMsg}`)}catch(error){let message=error instanceof Error?error.message:String(error);console.log(` \x1B[33m!\x1B[0m ${label.replace("...","")} failed: ${message}`)}}function performUninstall(hasHookScript,existingSymlinks,genieDir,hasGenieDir){if(hasHookScript)tryRemoveStep("Removing hook script...","Hook script removed",()=>removeHookScript());if(existingSymlinks.length>0){console.log("\x1B[2mRemoving symlinks...\x1B[0m");let removed=removeSymlinks();if(removed.length>0)console.log(` \x1B[32m+\x1B[0m Removed: ${removed.join(", ")}`)}if(existsSync24(ORCHESTRATION_RULES_PATH))tryRemoveStep("Removing orchestration rules...","Orchestration rules removed (~/.claude/rules/genie-orchestration.md)",()=>unlinkSync8(ORCHESTRATION_RULES_PATH));if(hasGenieDir)tryRemoveStep("Removing genie directory...","Directory removed",()=>rmSync2(genieDir,{recursive:!0,force:!0}))}async function uninstallCommand(){console.log(),console.log("\x1B[1m\x1B[33m Uninstall Genie CLI\x1B[0m"),console.log();let genieDir=getGenieDir(),hasGenieDir=existsSync24(genieDir),hasHookScript=hookScriptExists(),hasOrchestrationRules=existsSync24(ORCHESTRATION_RULES_PATH),existingSymlinks=SYMLINKS.filter((name)=>isGenieSymlink(join30(LOCAL_BIN,name)));if(console.log("\x1B[2mThis will remove:\x1B[0m"),hasHookScript)console.log(" \x1B[31m-\x1B[0m Hook script (~/.claude/hooks/genie-bash-hook.sh)");if(hasOrchestrationRules)console.log(" \x1B[31m-\x1B[0m Orchestration rules (~/.claude/rules/genie-orchestration.md)");if(hasGenieDir)console.log(` \x1B[31m-\x1B[0m Genie directory (${contractPath(genieDir)})`);if(existingSymlinks.length>0)console.log(` \x1B[31m-\x1B[0m Symlinks from ~/.local/bin: ${existingSymlinks.join(", ")}`);if(console.log(),!hasGenieDir&&!hasHookScript&&!hasOrchestrationRules&&existingSymlinks.length===0){console.log("\x1B[33mNothing to uninstall.\x1B[0m"),console.log();return}if(!await esm_default4({message:"Are you sure you want to uninstall Genie CLI?",default:!1})){console.log(),console.log("\x1B[2mUninstall cancelled.\x1B[0m"),console.log();return}console.log(),performUninstall(hasHookScript,existingSymlinks,genieDir,hasGenieDir),console.log(),console.log("\x1B[32m+\x1B[0m Genie CLI uninstalled."),console.log(),console.log("\x1B[2mNote: If you installed via npm/bun, also run:\x1B[0m"),console.log(" \x1B[36mbun remove -g @automagik/genie\x1B[0m"),console.log(" \x1B[2mor\x1B[0m"),console.log(" \x1B[36mnpm uninstall -g @automagik/genie\x1B[0m"),console.log()}init_genie_config2();import{execSync as execSync4,spawn as spawn3}from"child_process";import{chmodSync as chmodSync2,closeSync as closeSync3,copyFileSync as copyFileSync3,existsSync as existsSync25,mkdirSync as mkdirSync13,openSync as openSync3,readFileSync as readFileSync17,readSync as readSync2,readdirSync as readdirSync8,rmSync as rmSync3,statSync as statSync7,writeFileSync as writeFileSync11}from"fs";import{chmod,copyFile,mkdir as mkdir5,unlink as unlink2}from"fs/promises";import{homedir as homedir26}from"os";import{join as join31}from"path";var GENIE_HOME2=process.env.GENIE_HOME||join31(homedir26(),".genie"),GENIE_SRC=join31(GENIE_HOME2,"src"),GENIE_BIN=join31(GENIE_HOME2,"bin"),LOCAL_BIN2=join31(homedir26(),".local","bin"),TRUTHY=new Set(["1","true","yes","on"]),UPDATE_DIAGNOSTIC_SCHEMA_VERSION=1;function log(message){console.log(`\x1B[32m\u25B8\x1B[0m ${message}`)}function success(message){console.log(`\x1B[32m\u2714\x1B[0m ${message}`)}function error(message){console.log(`\x1B[31m\u2716\x1B[0m ${message}`)}function formatDuration2(ms){if(ms<1000)return`${ms}ms`;return`${(ms/1000).toFixed(1)}s`}function isTruthyEnv(value){return value!==void 0&&TRUTHY.has(value.trim().toLowerCase())}async function withTemporaryEnv(key,value,fn){let previous=process.env[key];process.env[key]=value;try{return await fn()}finally{if(previous===void 0)delete process.env[key];else process.env[key]=previous}}function safeExec(command,timeoutMs=1500){try{return execSync4(command,{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:timeoutMs}).trim()}catch(err){let stdout=err.stdout;if(typeof stdout==="string"&&stdout.trim())return stdout.trim();return""}}function safeRead(path3,maxChars=4000){try{let value=readFileSync17(path3,"utf-8");if(value.length<=maxChars)return value;return value.slice(value.length-maxChars)}catch{return null}}function tailLines(path3,maxBytes=64000,maxLines=200){let fd=null;try{let stat4=statSync7(path3),bytesToRead=Math.min(stat4.size,maxBytes),buffer2=Buffer.alloc(bytesToRead);return fd=openSync3(path3,"r"),readSync2(fd,buffer2,0,bytesToRead,Math.max(0,stat4.size-bytesToRead)),buffer2.toString("utf-8").split(/\r?\n/).map((line)=>line.trim()).filter(Boolean).slice(-maxLines)}catch{return[]}finally{if(fd!==null)try{closeSync3(fd)}catch{}}}function summarizeJsonlSignals(path3){let signals2=new Map;for(let line of tailLines(path3))try{let event=JSON.parse(line),level=typeof event.level==="string"?event.level:"unknown";if(level!=="error"&&level!=="warn")continue;let name=typeof event.event==="string"?event.event:"unknown",key=`${level}:${name}`,existing=signals2.get(key)??{level,event:name,count:0};if(existing.count++,typeof event.timestamp==="string")existing.lastTimestamp=event.timestamp;if(typeof event.error==="string")existing.lastError=event.error;signals2.set(key,existing)}catch{}return[...signals2.values()].sort((a,b2)=>b2.count-a.count).slice(0,10)}async function collectUpdateDiagnostics(ctx,maintenance){let logsDir=join31(GENIE_HOME2,"logs");mkdirSync13(logsDir,{recursive:!0});let generatedAt=new Date().toISOString(),safeStamp=generatedAt.replace(/[:.]/g,"-"),path3=join31(logsDir,`update-diagnostics-${safeStamp}.json`),schedulerLog=join31(logsDir,"scheduler.log"),tuiCrashLog=join31(logsDir,"tui-crash.log"),signals2=summarizeJsonlSignals(schedulerLog),diagnostics={schemaVersion:UPDATE_DIAGNOSTIC_SCHEMA_VERSION,generatedAt,update:ctx,runtime:{platform:process.platform,arch:process.arch,cwd:process.cwd(),node:process.version,bun:(await runCommandSilent("bun",["--version"])).output.trim()||null,npm:(await runCommandSilent("npm",["--version"])).output.trim()||null,genie:{which:(await runCommandSilent("which",["genie"])).output.trim()||null,tuiDisabled:isTruthyEnv(process.env.GENIE_TUI_DISABLE),updateSkipMaintenance:isTruthyEnv(process.env.GENIE_UPDATE_SKIP_MAINTENANCE)}},paths:{genieHome:GENIE_HOME2,logsDir,servePid:safeRead(join31(GENIE_HOME2,"serve.pid"),200),pgservePort:safeRead(join31(GENIE_HOME2,"pgserve.port"),200),schedulerLog,tuiCrashLog},processSnapshot:{genie:safeExec("ps -axo pid,ppid,pgid,stat,pcpu,pmem,etime,command -r | rg -i 'dist/genie.js|/src/genie.ts|pgserve|postgres -D .*\\.genie/data/pgserve|tmux -L genie-tui|bun' || true",2000)||null,tuiTmux:safeExec("tmux -L genie-tui ls 2>/dev/null || true",1000)||null},maintenance:{...maintenance,pgAutostartDisabled:!0,legend:{"[ok]":"healthy","[fix]":"fixed during maintenance","[--]":"skipped/non-blocking","[!!]":"operator action needed; update still completed"}},recentLogSignals:{scheduler:signals2,schedulerTail:tailLines(schedulerLog,32000,80),tuiCrashTail:tailLines(tuiCrashLog,32000,80)}};return writeFileSync11(path3,`${JSON.stringify(diagnostics,null,2)}
|
|
3858
|
-
`),{path:path3,signals:signals2}}async function runCommand(command,args,cwd){return new Promise((resolve4)=>{let output=[],child=spawn3(command,args,{cwd,stdio:["inherit","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"}});child.stdout?.on("data",(data)=>{let str2=data.toString();output.push(str2),process.stdout.write(str2)}),child.stderr?.on("data",(data)=>{let str2=data.toString();output.push(str2),process.stderr.write(str2)}),child.on("close",(code)=>{resolve4({success:code===0,output:output.join("")})}),child.on("error",(err)=>{error(err.message),resolve4({success:!1,output:err.message})})})}async function getGitInfo(cwd){try{let branchResult=await runCommandSilent("git",["rev-parse","--abbrev-ref","HEAD"],cwd),commitResult=await runCommandSilent("git",["rev-parse","--short","HEAD"],cwd),dateResult=await runCommandSilent("git",["log","-1","--format=%ci"],cwd);if(branchResult.success&&commitResult.success&&dateResult.success)return{branch:branchResult.output.trim(),commit:commitResult.output.trim(),commitDate:dateResult.output.trim().split(" ")[0]}}catch{}return null}async function runCommandSilent(command,args,cwd,timeoutMs=4000){return new Promise((resolve4)=>{let output=[],settled=!1,child=spawn3(command,args,{cwd,stdio:["inherit","pipe","pipe"]}),timer2=setTimeout(()=>{if(settled)return;settled=!0,child.kill("SIGTERM"),resolve4({success:!1,output:`Timed out after ${timeoutMs}ms`})},timeoutMs);child.stdout?.on("data",(data)=>{output.push(data.toString())}),child.stderr?.on("data",(data)=>{output.push(data.toString())}),child.on("close",(code)=>{if(settled)return;settled=!0,clearTimeout(timer2),resolve4({success:code===0,output:output.join("")})}),child.on("error",(err)=>{if(settled)return;settled=!0,clearTimeout(timer2),resolve4({success:!1,output:err.message})})})}function detectFromBinaryPath(path3){let resolved=path3;try{resolved=__require("fs").realpathSync(path3)}catch{}if(resolved.includes(".bun"))return"bun";if(resolved.includes("node_modules"))return"npm";if(path3===join31(LOCAL_BIN2,"genie")||resolved.startsWith(GENIE_BIN))return"source";return null}async function detectInstallationType(){let whichResult=await runCommandSilent("which",["genie"]);if(whichResult.success){let detected=detectFromBinaryPath(whichResult.output.trim());if(detected)return detected}if(genieConfigExists())try{let config=await loadGenieConfig();if(config.installMethod)return config.installMethod}catch{}if(existsSync25(join31(GENIE_SRC,".git")))return"source";return(await runCommandSilent("which",["bun"])).success?"bun":"npm"}async function updateViaBun(channel){try{__require("fs").unlinkSync(join31(homedir26(),".bun","install","global","bun.lock"))}catch{}if(log(`Updating via bun (channel: ${channel})...`),!(await runCommand("bun",["add","-g",`@automagik/genie@${channel}`])).success)return error("Failed to update via bun"),!1;return console.log(),success(`Genie CLI updated via bun (${channel})!`),!0}async function updateViaNpm(channel){if(log(`Updating via npm (channel: ${channel})...`),!(await runCommand("npm",["install","-g",`@automagik/genie@${channel}`])).success)return error("Failed to update via npm"),!1;return console.log(),success(`Genie CLI updated via npm (${channel})!`),!0}async function detectGlobalInstalls(){let found=new Set,[npmResult,bunResult]=await Promise.all([runCommandSilent("npm",["list","-g","@automagik/genie"]),runCommandSilent("bun",["pm","ls","-g"])]);if(npmResult.success&&!npmResult.output.includes("(empty)"))found.add("npm");if(bunResult.success&&bunResult.output.includes("@automagik/genie"))found.add("bun");return found}async function updateSource(){let beforeInfo=await getGitInfo(GENIE_SRC);if(beforeInfo)console.log(`Current: \x1B[2m${beforeInfo.branch}@${beforeInfo.commit} (${beforeInfo.commitDate})\x1B[0m`),console.log();if(log("Fetching latest changes..."),!(await runCommand("git",["fetch","origin"],GENIE_SRC)).success)error("Failed to fetch from origin"),process.exit(1);if(log("Resetting to origin/main..."),!(await runCommand("git",["reset","--hard","origin/main"],GENIE_SRC)).success)error("Failed to reset to origin/main"),process.exit(1);console.log();let afterInfo=await getGitInfo(GENIE_SRC);if(beforeInfo&&afterInfo&&beforeInfo.commit===afterInfo.commit){success("Already up to date!"),console.log();return}if(log("Installing dependencies..."),!(await runCommand("bun",["install"],GENIE_SRC)).success)error("Failed to install dependencies"),process.exit(1);if(console.log(),log("Building..."),!(await runCommand("bun",["run","build"],GENIE_SRC)).success)error("Failed to build"),process.exit(1);console.log(),log("Installing binaries...");try{await mkdir5(GENIE_BIN,{recursive:!0}),await mkdir5(LOCAL_BIN2,{recursive:!0});let binaries=["genie.js","term.js"],names=["genie","term"];for(let i2=0;i2<binaries.length;i2++){let src=join31(GENIE_SRC,"dist",binaries[i2]),binDest=join31(GENIE_BIN,binaries[i2]),linkDest=join31(LOCAL_BIN2,names[i2]);await copyFile(src,binDest),await chmod(binDest,493),await symlinkOrCopy(binDest,linkDest)}for(let legacy of["claudio.js","claudio"]){let legacyBin=join31(GENIE_BIN,legacy),legacyLink=join31(LOCAL_BIN2,legacy);try{await unlink2(legacyBin)}catch{}try{await unlink2(legacyLink)}catch{}}success("Binaries installed")}catch(err){error(`Failed to install binaries: ${err}`),process.exit(1)}if(console.log(),console.log("\x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),success("Genie CLI updated successfully!"),console.log(),afterInfo)console.log(`Version: \x1B[36m${afterInfo.branch}@${afterInfo.commit}\x1B[0m (${afterInfo.commitDate})`),console.log()}async function symlinkOrCopy(src,dest){let{symlink:symlink2,unlink:unlink3}=await import("fs/promises");try{if(existsSync25(dest))await unlink3(dest);await symlink2(src,dest)}catch{await copyFile(src,dest)}}function copyDirSync(src,dest){mkdirSync13(dest,{recursive:!0});for(let entry2 of readdirSync8(src,{withFileTypes:!0})){let srcPath=join31(src,entry2.name),destPath=join31(dest,entry2.name);if(entry2.isDirectory())copyDirSync(srcPath,destPath);else copyFileSync3(srcPath,destPath)}}async function resolveGlobalPkgDir(installType){if(installType==="bun"){let bunPath=join31(homedir26(),".bun","install","global","node_modules","@automagik","genie");if(existsSync25(bunPath))return bunPath}if(installType==="npm"){let npmRootResult=await runCommandSilent("npm",["root","-g"]);if(npmRootResult.success){let npmPath=join31(npmRootResult.output.trim(),"@automagik","genie");if(existsSync25(npmPath))return npmPath}}let bunFallback=join31(homedir26(),".bun","install","global","node_modules","@automagik","genie");if(existsSync25(bunFallback))return bunFallback;let npmRootFallback=await runCommandSilent("npm",["root","-g"]);if(npmRootFallback.success){let npmPath=join31(npmRootFallback.output.trim(),"@automagik","genie");if(existsSync25(npmPath))return npmPath}return null}function updatePluginRegistry(claudePlugins,cacheDir,version){let registryPath=join31(claudePlugins,"installed_plugins.json");try{if(!existsSync25(registryPath))return;let registry=JSON.parse(readFileSync17(registryPath,"utf-8")),entries=registry.plugins?.["genie@automagik"];if(!Array.isArray(entries))return;for(let entry2 of entries)if(entry2.scope==="user")entry2.installPath=cacheDir,entry2.version=version,entry2.lastUpdated=new Date().toISOString();writeFileSync11(registryPath,JSON.stringify(registry,null,2))}catch(err){log(`Registry update failed (non-fatal): ${err}`)}}function syncTmuxConf(tmuxScriptsSrc){mkdirSync13(GENIE_HOME2,{recursive:!0});let tmuxConfSrc=join31(tmuxScriptsSrc,"genie.tmux.conf"),tmuxConfDest=join31(GENIE_HOME2,"tmux.conf");if(existsSync25(tmuxConfSrc))try{copyFileSync3(tmuxConfSrc,tmuxConfDest),success(`Installed tmux config to ${tmuxConfDest}`);try{let{tmuxBin:tmuxBin2}=(init_ensure_tmux(),__toCommonJS(exports_ensure_tmux));execSync4(`${tmuxBin2()} -L genie source-file '${tmuxConfDest}'`,{stdio:"ignore"}),success("Reloaded genie tmux server configuration")}catch{}}catch{}let tuiConfSrc=join31(tmuxScriptsSrc,"tui-tmux.conf"),tuiConfDest=join31(GENIE_HOME2,"tui-tmux.conf");if(existsSync25(tuiConfSrc))try{copyFileSync3(tuiConfSrc,tuiConfDest),success(`Installed TUI tmux config to ${tuiConfDest}`)}catch{}let themeSrc=join31(tmuxScriptsSrc,".generated.theme.conf"),themeDest=join31(GENIE_HOME2,".generated.theme.conf");if(existsSync25(themeSrc))try{copyFileSync3(themeSrc,themeDest),success(`Installed tmux theme to ${themeDest}`)}catch{}let osc52Src=join31(tmuxScriptsSrc,"osc52-copy.sh"),osc52Dest=join31(GENIE_HOME2,"scripts","osc52-copy.sh");if(existsSync25(osc52Src))try{copyFileSync3(osc52Src,osc52Dest),chmodSync2(osc52Dest,493),success(`Installed OSC 52 clipboard helper to ${osc52Dest}`)}catch{}}function syncTmuxScripts(globalPkgDir){let tmuxScriptsSrc=join31(globalPkgDir,"scripts","tmux");if(!existsSync25(tmuxScriptsSrc))return;let scriptsDir=join31(GENIE_HOME2,"scripts");mkdirSync13(scriptsDir,{recursive:!0});let scriptCount=0;for(let entry2 of readdirSync8(tmuxScriptsSrc))if(entry2.endsWith(".sh")||entry2==="genie.tmux.conf"||entry2==="tui-tmux.conf"||entry2===".generated.theme.conf"){let src=join31(tmuxScriptsSrc,entry2),dest=join31(scriptsDir,entry2);copyFileSync3(src,dest);try{chmodSync2(dest,entry2.endsWith(".sh")?493:420)}catch{}scriptCount++}if(scriptCount>0)success(`Refreshed ${scriptCount} tmux scripts at ${scriptsDir}`);syncTmuxConf(tmuxScriptsSrc)}function syncMarketplaceVersion(claudePlugins,version){let marketplacePath=join31(claudePlugins,"marketplaces","automagik",".claude-plugin","marketplace.json");try{if(!existsSync25(marketplacePath))return;let data=JSON.parse(readFileSync17(marketplacePath,"utf-8"));if(Array.isArray(data.plugins)){for(let plugin of data.plugins)if(plugin.name==="genie")plugin.version=version}writeFileSync11(marketplacePath,JSON.stringify(data,null,2)),success(`Updated marketplace.json to v${version}`)}catch(err){log(`Marketplace version update failed (non-fatal): ${err}`)}}function syncPluginPackageVersion(claudePlugins,version){let pkgPath=join31(claudePlugins,"marketplaces","automagik","plugins","genie","package.json");try{if(!existsSync25(pkgPath))return;let data=JSON.parse(readFileSync17(pkgPath,"utf-8"));data.version=version,writeFileSync11(pkgPath,JSON.stringify(data,null,2)),success(`Updated plugin package.json to v${version}`)}catch(err){log(`Plugin package.json update failed (non-fatal): ${err}`)}}function syncSkillsSymlink(claudePlugins,version){let skillsLink=join31(claudePlugins,"marketplaces","automagik","plugins","genie","skills"),cacheSkills=join31("..","..","..","..","cache","automagik","genie",version,"skills");try{let{symlinkSync,unlinkSync:unlinkSync9,lstatSync:lstatSync2}=__require("fs");try{lstatSync2(skillsLink),unlinkSync9(skillsLink)}catch{}symlinkSync(cacheSkills,skillsLink),success(`Skills symlink \u2192 cache/${version}/skills`)}catch(err){log(`Skills symlink update failed (non-fatal): ${err}`)}}async function syncPlugin(installType){log("Syncing Claude Code plugin...");let globalPkgDir=await resolveGlobalPkgDir(installType);if(!globalPkgDir)return log("Could not find installed package \u2014 skipping plugin sync"),{skippedReason:"installed package not found"};let pluginSrc=join31(globalPkgDir,"plugins","genie");if(!existsSync25(pluginSrc))return log("Plugin source not found in package \u2014 skipping plugin sync"),{globalPkgDir,skippedReason:"plugin source not found in package"};let version;try{version=JSON.parse(readFileSync17(join31(globalPkgDir,"package.json"),"utf-8")).version}catch{return log("Could not read package version \u2014 skipping plugin sync"),{globalPkgDir,skippedReason:"could not read package version"}}let claudePlugins=join31(homedir26(),".claude","plugins"),cacheDir=join31(claudePlugins,"cache","automagik","genie",version);try{if(existsSync25(cacheDir))rmSync3(cacheDir,{recursive:!0,force:!0});copyDirSync(pluginSrc,cacheDir);let skillsSrc=join31(globalPkgDir,"skills");if(existsSync25(skillsSrc)&&!existsSync25(join31(cacheDir,"skills")))copyDirSync(skillsSrc,join31(cacheDir,"skills"))}catch(err){return error(`Failed to copy plugin: ${err}`),{version,globalPkgDir,cacheDir,skippedReason:`failed to copy plugin: ${err}`}}return updatePluginRegistry(claudePlugins,cacheDir,version),syncMarketplaceVersion(claudePlugins,version),syncPluginPackageVersion(claudePlugins,version),syncSkillsSymlink(claudePlugins,version),syncTmuxScripts(globalPkgDir),success(`Plugin synced to v${version}`),{version,globalPkgDir,cacheDir}}async function resolveChannel(options){if(options.next)return"next";if(options.stable)return"latest";if(genieConfigExists())try{let config=await loadGenieConfig();if(config.updateChannel)return config.updateChannel}catch{}return"latest"}async function persistChannel(channel){try{let config=await loadGenieConfig();config.updateChannel=channel,await saveGenieConfig(config)}catch{}}async function updateCommand(options={}){console.log(),console.log("\x1B[1m\uD83E\uDDDE Genie CLI Update\x1B[0m"),console.log("\x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),console.log();let channel=await resolveChannel(options);if(options.next||options.stable)await persistChannel(channel);let installType=await detectInstallationType();if(log(`Detected installation: ${installType}`),log(`Channel: ${channel}${channel==="next"?" (dev builds)":" (stable)"}`),console.log(),installType==="unknown")error("No Genie CLI installation found"),console.log(),console.log("Install method not configured. Please reinstall genie:"),console.log("\x1B[36m curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash\x1B[0m"),console.log(),process.exit(1);if(installType==="source"){await updateSource();return}let globalInstalls=await detectGlobalInstalls(),primaryMethod=installType;if(!(primaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))process.exit(1);let secondaryMethod=primaryMethod==="bun"?"npm":"bun";if(globalInstalls.has(secondaryMethod)){if(console.log(),log(`Also updating ${secondaryMethod}-global install...`),!(secondaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))error(`Secondary update via ${secondaryMethod} failed (non-blocking)`)}let plugin=await syncPlugin(installType);await runPostUpdateMaintenanceSafe(options,{channel,installType,primaryMethod,globalInstalls:[...globalInstalls].sort(),plugin})}function printPostUpdateMaintenanceIntro(){console.log(),log("Running post-update maintenance..."),console.log(" Purpose: make first launch after update fast and collect upgrade health signals."),console.log(" Checks: runtime partitions, watchdog status, session backfill drift, zombie rows, team config orphans."),console.log(" PG policy: read-only; uses an already-running pgserve when available and will not auto-start it."),console.log(" Legend: [ok]=healthy, [fix]=fixed, [--]=skipped/non-blocking, [!!]=operator action needed.")}async function runMaintenanceWithCapturedLines(maintenanceLines){let{runPostUpdateMaintenance:runPostUpdateMaintenance2}=await Promise.resolve().then(() => (init_doctor(),exports_doctor));await withTemporaryEnv("GENIE_PG_NO_AUTOSTART","1",()=>runPostUpdateMaintenance2({log:(line)=>{maintenanceLines.push(line),console.log(line)}}))}function printDiagnosticsSummary(diagnostics){if(log("Post-update diagnostics captured."),console.log(` Report: ${diagnostics.path}`),console.log(" Include this file when opening a GitHub issue; it contains install metadata, step output,"),console.log(" local process state, and recent scheduler/TUI log signals."),diagnostics.signals.length===0)return;console.log(" Recent scheduler signals:");for(let signal of diagnostics.signals.slice(0,3)){let errorDetail=signal.lastError?` \u2014 ${signal.lastError}`:"";console.log(` ${signal.level}:${signal.event} \xD7${signal.count}${errorDetail}`)}}async function capturePostUpdateDiagnostics(diagnosticsCtx,maintenance){if(!diagnosticsCtx)return;try{let diagnostics=await collectUpdateDiagnostics(diagnosticsCtx,maintenance);printDiagnosticsSummary(diagnostics)}catch(err){let msg=err instanceof Error?err.message:String(err);log(`Post-update diagnostics capture failed (non-fatal): ${msg}`)}}async function runPostUpdateMaintenanceSafe(options={},diagnosticsCtx){if(options.skipMaintenance||isTruthyEnv(process.env.GENIE_UPDATE_SKIP_MAINTENANCE)){log("Skipping post-update maintenance (requested).");return}let startedAt=Date.now(),maintenanceLines=[],outcome="completed",maintenanceError;try{printPostUpdateMaintenanceIntro(),await runMaintenanceWithCapturedLines(maintenanceLines),success(`Post-update maintenance complete (${formatDuration2(Date.now()-startedAt)}).`)}catch(err){outcome="failed",maintenanceError=err instanceof Error?err.message:String(err),error(`Post-update maintenance skipped: ${maintenanceError}`)}await capturePostUpdateDiagnostics(diagnosticsCtx,{outcome,durationMs:Date.now()-startedAt,lines:maintenanceLines,error:maintenanceError})}init_version();init_hooks();async function readStdin(){let chunks=[];for await(let chunk of Bun.stdin.stream())chunks.push(Buffer.from(chunk));return Buffer.concat(chunks).toString("utf-8")}async function dispatchAction(){process.env.GENIE_SKIP_DB_BOOT="1";let stdin=await readStdin();if(!stdin.trim())process.exit(0);let result2=await dispatch(stdin);if(result2)process.stdout.write(result2)}function registerHookNamespace(program2){program2.command("hook").description("Hook middleware for Claude Code integration").command("dispatch").description("Dispatch a CC hook event (reads JSON from stdin, writes decision to stdout)").action(dispatchAction)}init_audit();init_db();init_interactivity();init_otel_receiver();init_target_resolver();init_tmux();init_orchestrator();async function resolveOrcTarget(target){let resolved=await resolveTarget(target);return{paneId:resolved.paneId,session:resolved.session||target,label:formatResolvedLabel(resolved,target)}}async function sendTextChoice(paneId,text){await executeTmux2(`send-keys -t '${paneId}' End`),await sleep2(100),await executeTmux2(`send-keys -t '${paneId}' Enter`),await sleep2(100),await executeTmux2(`send-keys -t '${paneId}' ${shellEscape(text)}`),await sleep2(100),await executeTmux2(`send-keys -t '${paneId}' Enter`)}function findCurrentOption(output){let lines=stripAnsi(output).split(`
|
|
3858
|
+
`),{path:path3,signals:signals2}}async function runCommand(command,args,cwd){return new Promise((resolve4)=>{let output=[],child=spawn3(command,args,{cwd,stdio:["inherit","pipe","pipe"],env:{...process.env,FORCE_COLOR:"1"}});child.stdout?.on("data",(data)=>{let str2=data.toString();output.push(str2),process.stdout.write(str2)}),child.stderr?.on("data",(data)=>{let str2=data.toString();output.push(str2),process.stderr.write(str2)}),child.on("close",(code)=>{resolve4({success:code===0,output:output.join("")})}),child.on("error",(err)=>{error(err.message),resolve4({success:!1,output:err.message})})})}async function getGitInfo(cwd){try{let branchResult=await runCommandSilent("git",["rev-parse","--abbrev-ref","HEAD"],cwd),commitResult=await runCommandSilent("git",["rev-parse","--short","HEAD"],cwd),dateResult=await runCommandSilent("git",["log","-1","--format=%ci"],cwd);if(branchResult.success&&commitResult.success&&dateResult.success)return{branch:branchResult.output.trim(),commit:commitResult.output.trim(),commitDate:dateResult.output.trim().split(" ")[0]}}catch{}return null}async function runCommandSilent(command,args,cwd,timeoutMs=4000){return new Promise((resolve4)=>{let output=[],settled=!1,child=spawn3(command,args,{cwd,stdio:["inherit","pipe","pipe"]}),timer2=setTimeout(()=>{if(settled)return;settled=!0,child.kill("SIGTERM"),resolve4({success:!1,output:`Timed out after ${timeoutMs}ms`})},timeoutMs);child.stdout?.on("data",(data)=>{output.push(data.toString())}),child.stderr?.on("data",(data)=>{output.push(data.toString())}),child.on("close",(code)=>{if(settled)return;settled=!0,clearTimeout(timer2),resolve4({success:code===0,output:output.join("")})}),child.on("error",(err)=>{if(settled)return;settled=!0,clearTimeout(timer2),resolve4({success:!1,output:err.message})})})}function detectFromBinaryPath(path3){let resolved=path3;try{resolved=__require("fs").realpathSync(path3)}catch{}if(resolved.includes(".bun"))return"bun";if(resolved.includes("node_modules"))return"npm";if(path3===join31(LOCAL_BIN2,"genie")||resolved.startsWith(GENIE_BIN))return"source";return null}async function detectInstallationType(){let whichResult=await runCommandSilent("which",["genie"]);if(whichResult.success){let detected=detectFromBinaryPath(whichResult.output.trim());if(detected)return detected}if(genieConfigExists())try{let config=await loadGenieConfig();if(config.installMethod)return config.installMethod}catch{}if(existsSync25(join31(GENIE_SRC,".git")))return"source";return(await runCommandSilent("which",["bun"])).success?"bun":"npm"}async function updateViaBun(channel){try{__require("fs").unlinkSync(join31(homedir26(),".bun","install","global","bun.lock"))}catch{}if(log(`Updating via bun (channel: ${channel})...`),!(await runCommand("bun",["add","-g",`@automagik/genie@${channel}`])).success)return error("Failed to update via bun"),!1;return console.log(),success(`Genie CLI updated via bun (${channel})!`),!0}async function updateViaNpm(channel){if(log(`Updating via npm (channel: ${channel})...`),!(await runCommand("npm",["install","-g",`@automagik/genie@${channel}`])).success)return error("Failed to update via npm"),!1;return console.log(),success(`Genie CLI updated via npm (${channel})!`),!0}async function detectGlobalInstalls(){let found=new Set,[npmResult,bunResult]=await Promise.all([runCommandSilent("npm",["list","-g","@automagik/genie"]),runCommandSilent("bun",["pm","ls","-g"])]);if(npmResult.success&&!npmResult.output.includes("(empty)"))found.add("npm");if(bunResult.success&&bunResult.output.includes("@automagik/genie"))found.add("bun");return found}async function updateSource(){if(!existsSync25(GENIE_SRC))error(`Source install path not found: ${GENIE_SRC}`),console.error(" Detection picked the source-install path, but the directory does not exist."),console.error(" This usually means a stale install hint (config or ~/.genie/src/.git) is"),console.error(" pointing somewhere genuine. Either:"),console.error(` 1. Re-clone the source: git clone https://github.com/automagik-dev/genie ${GENIE_SRC}`),console.error(" 2. Update via package manager instead: genie update --next --via bun"),console.error(" 3. Inspect detection: genie doctor --update-detection"),process.exit(1);if(!existsSync25(join31(GENIE_SRC,".git")))error(`Source install path is not a git checkout: ${GENIE_SRC}`),console.error(` ${GENIE_SRC} exists but has no .git/. Cannot run \`git fetch\` from it.`),console.error(` Either delete ${GENIE_SRC} and re-clone, or update via package manager:`),console.error(" genie update --next --via bun"),process.exit(1);let beforeInfo=await getGitInfo(GENIE_SRC);if(beforeInfo)console.log(`Current: \x1B[2m${beforeInfo.branch}@${beforeInfo.commit} (${beforeInfo.commitDate})\x1B[0m`),console.log();if(log("Fetching latest changes..."),!(await runCommand("git",["fetch","origin"],GENIE_SRC)).success)error("Failed to fetch from origin"),process.exit(1);if(log("Resetting to origin/main..."),!(await runCommand("git",["reset","--hard","origin/main"],GENIE_SRC)).success)error("Failed to reset to origin/main"),process.exit(1);console.log();let afterInfo=await getGitInfo(GENIE_SRC);if(beforeInfo&&afterInfo&&beforeInfo.commit===afterInfo.commit){success("Already up to date!"),console.log();return}if(log("Installing dependencies..."),!(await runCommand("bun",["install"],GENIE_SRC)).success)error("Failed to install dependencies"),process.exit(1);if(console.log(),log("Building..."),!(await runCommand("bun",["run","build"],GENIE_SRC)).success)error("Failed to build"),process.exit(1);console.log(),log("Installing binaries...");try{await mkdir5(GENIE_BIN,{recursive:!0}),await mkdir5(LOCAL_BIN2,{recursive:!0});let binaries=["genie.js","term.js"],names=["genie","term"];for(let i2=0;i2<binaries.length;i2++){let src=join31(GENIE_SRC,"dist",binaries[i2]),binDest=join31(GENIE_BIN,binaries[i2]),linkDest=join31(LOCAL_BIN2,names[i2]);await copyFile(src,binDest),await chmod(binDest,493),await symlinkOrCopy(binDest,linkDest)}for(let legacy of["claudio.js","claudio"]){let legacyBin=join31(GENIE_BIN,legacy),legacyLink=join31(LOCAL_BIN2,legacy);try{await unlink2(legacyBin)}catch{}try{await unlink2(legacyLink)}catch{}}success("Binaries installed")}catch(err){error(`Failed to install binaries: ${err}`),process.exit(1)}if(console.log(),console.log("\x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),success("Genie CLI updated successfully!"),console.log(),afterInfo)console.log(`Version: \x1B[36m${afterInfo.branch}@${afterInfo.commit}\x1B[0m (${afterInfo.commitDate})`),console.log()}async function symlinkOrCopy(src,dest){let{symlink:symlink2,unlink:unlink3}=await import("fs/promises");try{if(existsSync25(dest))await unlink3(dest);await symlink2(src,dest)}catch{await copyFile(src,dest)}}function copyDirSync(src,dest){mkdirSync13(dest,{recursive:!0});for(let entry2 of readdirSync8(src,{withFileTypes:!0})){let srcPath=join31(src,entry2.name),destPath=join31(dest,entry2.name);if(entry2.isDirectory())copyDirSync(srcPath,destPath);else copyFileSync3(srcPath,destPath)}}async function resolveGlobalPkgDir(installType){if(installType==="bun"){let bunPath=join31(homedir26(),".bun","install","global","node_modules","@automagik","genie");if(existsSync25(bunPath))return bunPath}if(installType==="npm"){let npmRootResult=await runCommandSilent("npm",["root","-g"]);if(npmRootResult.success){let npmPath=join31(npmRootResult.output.trim(),"@automagik","genie");if(existsSync25(npmPath))return npmPath}}let bunFallback=join31(homedir26(),".bun","install","global","node_modules","@automagik","genie");if(existsSync25(bunFallback))return bunFallback;let npmRootFallback=await runCommandSilent("npm",["root","-g"]);if(npmRootFallback.success){let npmPath=join31(npmRootFallback.output.trim(),"@automagik","genie");if(existsSync25(npmPath))return npmPath}return null}function updatePluginRegistry(claudePlugins,cacheDir,version){let registryPath=join31(claudePlugins,"installed_plugins.json");try{if(!existsSync25(registryPath))return;let registry=JSON.parse(readFileSync17(registryPath,"utf-8")),entries=registry.plugins?.["genie@automagik"];if(!Array.isArray(entries))return;for(let entry2 of entries)if(entry2.scope==="user")entry2.installPath=cacheDir,entry2.version=version,entry2.lastUpdated=new Date().toISOString();writeFileSync11(registryPath,JSON.stringify(registry,null,2))}catch(err){log(`Registry update failed (non-fatal): ${err}`)}}function syncTmuxConf(tmuxScriptsSrc){mkdirSync13(GENIE_HOME2,{recursive:!0});let tmuxConfSrc=join31(tmuxScriptsSrc,"genie.tmux.conf"),tmuxConfDest=join31(GENIE_HOME2,"tmux.conf");if(existsSync25(tmuxConfSrc))try{copyFileSync3(tmuxConfSrc,tmuxConfDest),success(`Installed tmux config to ${tmuxConfDest}`);try{let{tmuxBin:tmuxBin2}=(init_ensure_tmux(),__toCommonJS(exports_ensure_tmux));execSync4(`${tmuxBin2()} -L genie source-file '${tmuxConfDest}'`,{stdio:"ignore"}),success("Reloaded genie tmux server configuration")}catch{}}catch{}let tuiConfSrc=join31(tmuxScriptsSrc,"tui-tmux.conf"),tuiConfDest=join31(GENIE_HOME2,"tui-tmux.conf");if(existsSync25(tuiConfSrc))try{copyFileSync3(tuiConfSrc,tuiConfDest),success(`Installed TUI tmux config to ${tuiConfDest}`)}catch{}let themeSrc=join31(tmuxScriptsSrc,".generated.theme.conf"),themeDest=join31(GENIE_HOME2,".generated.theme.conf");if(existsSync25(themeSrc))try{copyFileSync3(themeSrc,themeDest),success(`Installed tmux theme to ${themeDest}`)}catch{}let osc52Src=join31(tmuxScriptsSrc,"osc52-copy.sh"),osc52Dest=join31(GENIE_HOME2,"scripts","osc52-copy.sh");if(existsSync25(osc52Src))try{copyFileSync3(osc52Src,osc52Dest),chmodSync2(osc52Dest,493),success(`Installed OSC 52 clipboard helper to ${osc52Dest}`)}catch{}}function syncTmuxScripts(globalPkgDir){let tmuxScriptsSrc=join31(globalPkgDir,"scripts","tmux");if(!existsSync25(tmuxScriptsSrc))return;let scriptsDir=join31(GENIE_HOME2,"scripts");mkdirSync13(scriptsDir,{recursive:!0});let scriptCount=0;for(let entry2 of readdirSync8(tmuxScriptsSrc))if(entry2.endsWith(".sh")||entry2==="genie.tmux.conf"||entry2==="tui-tmux.conf"||entry2===".generated.theme.conf"){let src=join31(tmuxScriptsSrc,entry2),dest=join31(scriptsDir,entry2);copyFileSync3(src,dest);try{chmodSync2(dest,entry2.endsWith(".sh")?493:420)}catch{}scriptCount++}if(scriptCount>0)success(`Refreshed ${scriptCount} tmux scripts at ${scriptsDir}`);syncTmuxConf(tmuxScriptsSrc)}function syncMarketplaceVersion(claudePlugins,version){let marketplacePath=join31(claudePlugins,"marketplaces","automagik",".claude-plugin","marketplace.json");try{if(!existsSync25(marketplacePath))return;let data=JSON.parse(readFileSync17(marketplacePath,"utf-8"));if(Array.isArray(data.plugins)){for(let plugin of data.plugins)if(plugin.name==="genie")plugin.version=version}writeFileSync11(marketplacePath,JSON.stringify(data,null,2)),success(`Updated marketplace.json to v${version}`)}catch(err){log(`Marketplace version update failed (non-fatal): ${err}`)}}function syncPluginPackageVersion(claudePlugins,version){let pkgPath=join31(claudePlugins,"marketplaces","automagik","plugins","genie","package.json");try{if(!existsSync25(pkgPath))return;let data=JSON.parse(readFileSync17(pkgPath,"utf-8"));data.version=version,writeFileSync11(pkgPath,JSON.stringify(data,null,2)),success(`Updated plugin package.json to v${version}`)}catch(err){log(`Plugin package.json update failed (non-fatal): ${err}`)}}function syncSkillsSymlink(claudePlugins,version){let skillsLink=join31(claudePlugins,"marketplaces","automagik","plugins","genie","skills"),cacheSkills=join31("..","..","..","..","cache","automagik","genie",version,"skills");try{let{symlinkSync,unlinkSync:unlinkSync9,lstatSync:lstatSync2}=__require("fs");try{lstatSync2(skillsLink),unlinkSync9(skillsLink)}catch{}symlinkSync(cacheSkills,skillsLink),success(`Skills symlink \u2192 cache/${version}/skills`)}catch(err){log(`Skills symlink update failed (non-fatal): ${err}`)}}async function syncPlugin(installType){log("Syncing Claude Code plugin...");let globalPkgDir=await resolveGlobalPkgDir(installType);if(!globalPkgDir)return log("Could not find installed package \u2014 skipping plugin sync"),{skippedReason:"installed package not found"};let pluginSrc=join31(globalPkgDir,"plugins","genie");if(!existsSync25(pluginSrc))return log("Plugin source not found in package \u2014 skipping plugin sync"),{globalPkgDir,skippedReason:"plugin source not found in package"};let version;try{version=JSON.parse(readFileSync17(join31(globalPkgDir,"package.json"),"utf-8")).version}catch{return log("Could not read package version \u2014 skipping plugin sync"),{globalPkgDir,skippedReason:"could not read package version"}}let claudePlugins=join31(homedir26(),".claude","plugins"),cacheDir=join31(claudePlugins,"cache","automagik","genie",version);try{if(existsSync25(cacheDir))rmSync3(cacheDir,{recursive:!0,force:!0});copyDirSync(pluginSrc,cacheDir);let skillsSrc=join31(globalPkgDir,"skills");if(existsSync25(skillsSrc)&&!existsSync25(join31(cacheDir,"skills")))copyDirSync(skillsSrc,join31(cacheDir,"skills"))}catch(err){return error(`Failed to copy plugin: ${err}`),{version,globalPkgDir,cacheDir,skippedReason:`failed to copy plugin: ${err}`}}return updatePluginRegistry(claudePlugins,cacheDir,version),syncMarketplaceVersion(claudePlugins,version),syncPluginPackageVersion(claudePlugins,version),syncSkillsSymlink(claudePlugins,version),syncTmuxScripts(globalPkgDir),success(`Plugin synced to v${version}`),{version,globalPkgDir,cacheDir}}async function resolveChannel(options){if(options.next)return"next";if(options.stable)return"latest";if(genieConfigExists())try{let config=await loadGenieConfig();if(config.updateChannel)return config.updateChannel}catch{}return"latest"}async function persistChannel(channel){try{let config=await loadGenieConfig();config.updateChannel=channel,await saveGenieConfig(config)}catch{}}async function updateCommand(options={}){console.log(),console.log("\x1B[1m\uD83E\uDDDE Genie CLI Update\x1B[0m"),console.log("\x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),console.log();let channel=await resolveChannel(options);if(options.next||options.stable)await persistChannel(channel);let installType=await detectInstallationType();if(log(`Detected installation: ${installType}`),log(`Channel: ${channel}${channel==="next"?" (dev builds)":" (stable)"}`),console.log(),installType==="unknown")error("No Genie CLI installation found"),console.log(),console.log("Install method not configured. Please reinstall genie:"),console.log("\x1B[36m curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash\x1B[0m"),console.log(),process.exit(1);if(installType==="source"){await updateSource();return}let globalInstalls=await detectGlobalInstalls(),primaryMethod=installType;if(!(primaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))process.exit(1);let secondaryMethod=primaryMethod==="bun"?"npm":"bun";if(globalInstalls.has(secondaryMethod)){if(console.log(),log(`Also updating ${secondaryMethod}-global install...`),!(secondaryMethod==="bun"?await updateViaBun(channel):await updateViaNpm(channel)))error(`Secondary update via ${secondaryMethod} failed (non-blocking)`)}let plugin=await syncPlugin(installType);await runPostUpdateMaintenanceSafe(options,{channel,installType,primaryMethod,globalInstalls:[...globalInstalls].sort(),plugin})}function printPostUpdateMaintenanceIntro(){console.log(),log("Running post-update maintenance..."),console.log(" Purpose: make first launch after update fast and collect upgrade health signals."),console.log(" Checks: runtime partitions, watchdog status, session backfill drift, zombie rows, team config orphans."),console.log(" PG policy: read-only; uses an already-running pgserve when available and will not auto-start it."),console.log(" Legend: [ok]=healthy, [fix]=fixed, [--]=skipped/non-blocking, [!!]=operator action needed.")}async function runMaintenanceWithCapturedLines(maintenanceLines){let{runPostUpdateMaintenance:runPostUpdateMaintenance2}=await Promise.resolve().then(() => (init_doctor(),exports_doctor));await withTemporaryEnv("GENIE_PG_NO_AUTOSTART","1",()=>runPostUpdateMaintenance2({log:(line)=>{maintenanceLines.push(line),console.log(line)}}))}function printDiagnosticsSummary(diagnostics){if(log("Post-update diagnostics captured."),console.log(` Report: ${diagnostics.path}`),console.log(" Include this file when opening a GitHub issue; it contains install metadata, step output,"),console.log(" local process state, and recent scheduler/TUI log signals."),diagnostics.signals.length===0)return;console.log(" Recent scheduler signals:");for(let signal of diagnostics.signals.slice(0,3)){let errorDetail=signal.lastError?` \u2014 ${signal.lastError}`:"";console.log(` ${signal.level}:${signal.event} \xD7${signal.count}${errorDetail}`)}}async function capturePostUpdateDiagnostics(diagnosticsCtx,maintenance){if(!diagnosticsCtx)return;try{let diagnostics=await collectUpdateDiagnostics(diagnosticsCtx,maintenance);printDiagnosticsSummary(diagnostics)}catch(err){let msg=err instanceof Error?err.message:String(err);log(`Post-update diagnostics capture failed (non-fatal): ${msg}`)}}async function runPostUpdateMaintenanceSafe(options={},diagnosticsCtx){if(options.skipMaintenance||isTruthyEnv(process.env.GENIE_UPDATE_SKIP_MAINTENANCE)){log("Skipping post-update maintenance (requested).");return}let startedAt=Date.now(),maintenanceLines=[],outcome="completed",maintenanceError;try{printPostUpdateMaintenanceIntro(),await runMaintenanceWithCapturedLines(maintenanceLines),success(`Post-update maintenance complete (${formatDuration2(Date.now()-startedAt)}).`)}catch(err){outcome="failed",maintenanceError=err instanceof Error?err.message:String(err),error(`Post-update maintenance skipped: ${maintenanceError}`)}await capturePostUpdateDiagnostics(diagnosticsCtx,{outcome,durationMs:Date.now()-startedAt,lines:maintenanceLines,error:maintenanceError})}init_version();init_hooks();async function readStdin(){let chunks=[];for await(let chunk of Bun.stdin.stream())chunks.push(Buffer.from(chunk));return Buffer.concat(chunks).toString("utf-8")}async function dispatchAction(){process.env.GENIE_SKIP_DB_BOOT="1";let stdin=await readStdin();if(!stdin.trim())process.exit(0);let result2=await dispatch(stdin);if(result2)process.stdout.write(result2)}function registerHookNamespace(program2){program2.command("hook").description("Hook middleware for Claude Code integration").command("dispatch").description("Dispatch a CC hook event (reads JSON from stdin, writes decision to stdout)").action(dispatchAction)}init_audit();init_db();init_interactivity();init_otel_receiver();init_target_resolver();init_tmux();init_orchestrator();async function resolveOrcTarget(target){let resolved=await resolveTarget(target);return{paneId:resolved.paneId,session:resolved.session||target,label:formatResolvedLabel(resolved,target)}}async function sendTextChoice(paneId,text){await executeTmux2(`send-keys -t '${paneId}' End`),await sleep2(100),await executeTmux2(`send-keys -t '${paneId}' Enter`),await sleep2(100),await executeTmux2(`send-keys -t '${paneId}' ${shellEscape(text)}`),await sleep2(100),await executeTmux2(`send-keys -t '${paneId}' Enter`)}function findCurrentOption(output){let lines=stripAnsi(output).split(`
|
|
3859
3859
|
`);for(let line of lines){let match=line.match(/^\s*\u276F\s*(\d+)\./);if(match)return Number.parseInt(match[1],10)}return 1}async function navigateToOption(paneId,targetOption,currentOption){let diff=targetOption-currentOption,key=diff>0?"Down":"Up";for(let i2=0;i2<Math.abs(diff);i2++)await executeTmux2(`send-keys -t '${paneId}' ${key}`),await sleep2(50);await sleep2(100),await executeTmux2(`send-keys -t '${paneId}' Enter`)}async function answerQuestion(target,choice){try{let{paneId,label}=await resolveOrcTarget(target),output=await capturePaneContent(paneId,50),state=detectState(output);if(state.type!=="question"){console.log(`No question pending (state: ${state.type})`);return}if(choice.startsWith("text:")){let text=choice.slice(5);await sendTextChoice(paneId,text),console.log(`Sent feedback: "${text.substring(0,50)}${text.length>50?"...":""}"`)}else if(/^\d+$/.test(choice)){let targetOption=Number.parseInt(choice,10);await navigateToOption(paneId,targetOption,findCurrentOption(output)),console.log(`Selected option ${targetOption} for ${label}`)}else await executeTmux2(`send-keys -t '${paneId}' '${choice}'`),console.log(`Sent '${choice}' to ${label}`)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}}function shellEscape(str2){return`"${str2.replace(/"/g,"\\\"").replace(/\$/g,"\\$")}"`}function sleep2(ms){return new Promise((resolve6)=>setTimeout(resolve6,ms))}function registerAgentAnswer(parent){parent.command("answer <name> <choice>").description('Answer a question for an agent (use "text:..." for text input)').action(async(name,choice)=>{try{await answerQuestion(name,choice)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(`Error: ${message}`),process.exit(1)}})}var _brief;async function getBrief(){if(!_brief)_brief=await Promise.resolve().then(() => (init_brief(),exports_brief));return _brief}async function handleBrief(options){let team=options.team??process.env.GENIE_TEAM;if(!team)console.error("Error: --team is required (or set GENIE_TEAM)"),process.exit(1);let agent=options.agent??process.env.GENIE_AGENT_NAME,briefService=await getBrief(),brief=await briefService.generateBrief({team,agent,since:options.since,repoPath:process.cwd()});console.log(briefService.formatBrief(brief))}function registerAgentBrief(parent){parent.command("brief").description("Show startup brief \u2014 aggregated context since last session").option("--team <name>","Team name (default: GENIE_TEAM)").option("--agent <name>","Agent name (default: GENIE_AGENT_NAME)").option("--since <iso>","Start timestamp (default: last executor end)").action(async(options)=>{try{await handleBrief(options)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}})}init_agent_directory();init_agent_sync();init_builtin_agents();init_genie_config2();async function showEntry(name,json2){let resolved=await resolve5(name);if(!resolved)console.error(`Agent "${name}" not found in directory or built-ins.`),process.exit(1);if(json2){console.log(JSON.stringify({...resolved.entry,builtin:resolved.builtin},null,2));return}if(resolved.builtin)console.log(`
|
|
3860
3860
|
(built-in agent)`);if(console.log(""),console.log(` Name: ${resolved.entry.name}`),console.log(` Dir: ${contractPath(resolved.entry.dir)}`),resolved.entry.repo)console.log(` Repo: ${contractPath(resolved.entry.repo)}`);if(console.log(` Prompt mode: ${resolved.entry.promptMode}`),resolved.entry.model)console.log(` Model: ${resolved.entry.model}`);if(resolved.entry.roles?.length)console.log(` Roles: ${resolved.entry.roles.join(", ")}`);console.log(` Registered: ${resolved.entry.registeredAt}`),console.log("")}function printRegisteredAgentsTable(entries){let termW=process.stdout.columns||120,repoValues=entries.map((e)=>e.repo?contractPath(e.repo):contractPath(e.dir)),maxRepoLen=Math.max(4,...repoValues.map((v)=>v.length)),fixedW=42,repoW=Math.min(maxRepoLen+2,Math.max(30,termW-42-20));console.log(""),console.log("REGISTERED AGENTS"),console.log("-".repeat(Math.max(90,42+repoW+20))),console.log(` ${"NAME".padEnd(22)}${"SCOPE".padEnd(10)}${"REPO".padEnd(repoW)}${"MODEL".padEnd(8)}ROLES`);for(let i2=0;i2<entries.length;i2++){let entry2=entries[i2],repo=repoValues[i2],roles=entry2.roles?.join(", ")||"-";console.log(` ${entry2.name.padEnd(22)}${entry2.scope.padEnd(10)}${repo.padEnd(repoW)}${(entry2.model||"-").padEnd(8)}${roles}`)}console.log("")}function printBuiltinAgentsTable(){console.log("BUILT-IN AGENTS"),console.log("-".repeat(80)),console.log(` ${"NAME".padEnd(22)}${"TYPE".padEnd(10)}${"MODEL".padEnd(8)}DESCRIPTION`);for(let agent of ALL_BUILTINS)console.log(` ${agent.name.padEnd(22)}${agent.category.padEnd(10)}${(agent.model||"-").padEnd(8)}${agent.description}`);console.log("")}async function listEntries(json2,includeBuiltins,_includeArchived){let entries=await ls();if(json2){let result2=entries.map((e)=>({...e,builtin:!1}));if(includeBuiltins)for(let b2 of ALL_BUILTINS)result2.push({name:b2.name,description:b2.description,model:b2.model,category:b2.category,scope:"built-in",builtin:!0});console.log(JSON.stringify(result2,null,2));return}if(entries.length===0&&!includeBuiltins){console.log(`
|
|
3861
3861
|
No agents registered. Add one with: genie agent register <name> --dir <path>`),console.log(`Use --builtins to also see built-in roles and council members.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@automagik/genie",
|
|
3
|
-
"version": "4.260429.
|
|
3
|
+
"version": "4.260429.25",
|
|
4
4
|
"description": "Collaborative terminal toolkit for human + AI workflows. NOTE: the npm distribution is being soft-deprecated — the canonical install is `curl -fsSL https://get.automagik.dev/genie | bash` (cosign + SLSA verified). See https://automagik.dev/genie/security/distribution-sovereignty",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "genie",
|
|
3
|
-
"version": "4.260429.
|
|
3
|
+
"version": "4.260429.25",
|
|
4
4
|
"description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Namastex Labs"
|