Files
thedotmack__claude-mem/plugin/scripts/transcript-watcher.cjs
T
2026-08-03 14:26:10 -07:00

30 lines
74 KiB
JavaScript
Executable File

#!/usr/bin/env bun
"use strict";var tn=Object.create;var Rt=Object.defineProperty;var rn=Object.getOwnPropertyDescriptor;var nn=Object.getOwnPropertyNames;var on=Object.getPrototypeOf,sn=Object.prototype.hasOwnProperty;var Se=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var an=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nn(e))!sn.call(r,o)&&o!==t&&Rt(r,o,{get:()=>e[o],enumerable:!(n=rn(e,o))||n.enumerable});return r};var X=(r,e,t)=>(t=r!=null?tn(on(r)):{},an(e||!r||!r.__esModule?Rt(t,"default",{value:r,enumerable:!0}):t,r));function Ze(r){return(cn??process.stderr.write.bind(process.stderr))(r)}function ee(r){Ze(r)}function At(r,e={}){he&&he.length>0&&(Ze(he.join("")),he=[]),Ze(r.endsWith(`
`)?r:`${r}
`),e.skipExit||process.exit(2)}var cn,he,ye=Se(()=>{"use strict";cn=null;he=null});function un(r){return r.replace(/^\uFEFF/,"")}function K(r){return JSON.parse(un(r))}function dn(r){(0,p.existsSync)(r)||(0,p.mkdirSync)(r,{recursive:!0})}function Te(r,e){let t=r;try{if((0,p.lstatSync)(r).isSymbolicLink())try{t=(0,p.realpathSync)(r)}catch(d){let u=d instanceof Error?d:new Error(String(d));ee(`claude-mem: realpathSync failed for ${r}, resolving symlink manually: ${u.message}
`);let E=(0,p.readlinkSync)(r);t=(0,D.resolve)((0,D.dirname)(r),E)}}catch(d){let u=d.code;if(u!=="ENOENT"&&u!=="ENOTDIR")throw d}dn((0,D.dirname)(t));let n=(0,D.dirname)(t),o=(0,D.basename)(t),i=(0,D.join)(n,`.${o}.${process.pid}.${(0,kt.randomBytes)(6).toString("hex")}.tmp`),s=Buffer.from(JSON.stringify(e,null,2)+`
`,"utf-8"),c;try{c=(0,p.statSync)(t).mode&511}catch{}let l;try{l=c!==void 0?(0,p.openSync)(i,"w",c):(0,p.openSync)(i,"w");let d=0;for(;d<s.length;){let u=(0,p.writeSync)(l,s,d,s.length-d);if(u===0)throw new Error(`writeSync stalled at ${d}/${s.length} bytes`);d+=u}if((0,p.fsyncSync)(l),(0,p.closeSync)(l),l=void 0,(0,p.renameSync)(i,t),!ln){let u;try{u=(0,p.openSync)(n,"r"),(0,p.fsyncSync)(u)}catch(E){let g=E instanceof Error?E:new Error(String(E));ee(`claude-mem: directory fsync failed for ${n}: ${g.message}
`)}finally{if(u!==void 0)try{(0,p.closeSync)(u)}catch{}}}}catch(d){if(l!==void 0)try{(0,p.closeSync)(l)}catch{}try{(0,p.unlinkSync)(i)}catch{}throw d}}var p,kt,D,ln,ce=Se(()=>{"use strict";p=require("fs"),kt=require("crypto"),D=require("path");ye();ln=process.platform==="win32"});function pn(){return typeof __dirname<"u"?__dirname:(0,m.dirname)((0,Ot.fileURLToPath)(En.url))}function It(r){return typeof r!="string"||r.length===0?r:r==="~"?(0,le.homedir)():r.startsWith("~/")?(0,m.join)((0,le.homedir)(),r.slice(2)):r}function te(){if(process.env.CLAUDE_MEM_DATA_DIR)return It(process.env.CLAUDE_MEM_DATA_DIR);let r=(0,m.join)((0,le.homedir)(),".claude-mem"),e=(0,m.join)(r,"settings.json");try{if((0,ue.existsSync)(e)){let t=K((0,ue.readFileSync)(e,"utf-8")),n=t.env??t;if(n.CLAUDE_MEM_DATA_DIR)return It(n.CLAUDE_MEM_DATA_DIR)}}catch{}return r}var m,le,ue,Ot,En,Xo,S,fn,we,mn,re,zo,et,gn,y,w=Se(()=>{"use strict";m=require("path"),le=require("os"),ue=require("fs"),Ot=require("url");ce();En={};Xo=pn();S=te(),fn=process.env.CLAUDE_CONFIG_DIR||(0,m.join)((0,le.homedir)(),".claude"),we=(0,m.join)(fn,"plugins","marketplaces","thedotmack"),mn=(0,m.join)(S,"logs"),re=(0,m.join)(S,"settings.json"),zo=(0,m.join)(S,"claude-mem.db"),et=(0,m.join)(S,"observer-sessions"),gn=(0,m.basename)(et),y={dataDir:()=>S,workerPid:()=>(0,m.join)(S,"worker.pid"),serverPid:()=>(0,m.join)(S,".server-beta.pid"),serverPort:()=>(0,m.join)(S,".server-beta.port"),serverRuntime:()=>(0,m.join)(S,".server-beta.runtime.json"),settings:()=>(0,m.join)(S,"settings.json"),database:()=>(0,m.join)(S,"claude-mem.db"),chroma:()=>(0,m.join)(S,"chroma"),combinedCerts:()=>(0,m.join)(S,"combined_certs.pem"),transcriptsConfig:()=>(0,m.join)(S,"transcript-watch.json"),transcriptsState:()=>(0,m.join)(S,"transcript-watch-state.json"),corpora:()=>(0,m.join)(S,"corpora"),supervisorRegistry:()=>(0,m.join)(S,"supervisor.json"),envFile:()=>(0,m.join)(S,".env"),logsDir:()=>mn}});var U,Pt,nt,rt,ot,a,f=Se(()=>{"use strict";U=require("fs"),Pt=require("path");w();ye();ce();nt=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(nt||{}),rt=null,ot=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=y.logsDir();(0,U.existsSync)(e)||(0,U.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,Pt.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=y.settings();if((0,U.existsSync)(e)){let t=(0,U.readFileSync)(e,"utf-8"),o=(K(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=nt[o]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=t}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${n}-${o} ${i}:${s}:${c}.${l}`}log(e,t,n,o,i){if(e<this.getLevel())return;this.ensureLogFileInitialized();let s=this.formatTimestamp(new Date),c=nt[e].padEnd(5),l=t.padEnd(6),d="";o?.correlationId?d=`[${o.correlationId}] `:o?.sessionId&&(d=`[session-${o.sessionId}] `);let u="";if(i!=null)if(i instanceof Error)u=this.getLevel()===0?`
${i.message}
${i.stack}`:` ${i.message}`;else if(this.getLevel()===0&&typeof i=="object")try{u=`
`+JSON.stringify(i,null,2)}catch{u=" "+this.formatData(i)}else u=" "+this.formatData(i);let E="";if(o){let{sessionId:M,memorySessionId:_,correlationId:Y,..._e}=o;Object.keys(_e).length>0&&(E=` {${Object.entries(_e).map(([q,en])=>`${q}=${en}`).join(", ")}}`)}let g=`[${s}] [${c}] [${l}] ${d}${n}${E}${u}`;if(this.logFilePath)try{(0,U.appendFileSync)(this.logFilePath,g+`
`,"utf8")}catch(M){let _=M instanceof Error?M:new Error(String(M));ee(`[LOGGER] Failed to write to log file: ${_.message}
${_.stack??""}
`)}else ee(g+`
`)}debug(e,t,n,o){this.log(0,e,t,n,o)}info(e,t,n,o){this.log(1,e,t,n,o)}warn(e,t,n,o){this.log(2,e,t,n,o)}setErrorSink(e){rt=e}error(e,t,n,o){this.log(3,e,t,n,o),this.routeErrorToSink(t,n,o)}routeErrorToSink(e,t,n){try{if(!rt||!(n instanceof Error))return;rt(n)}catch{}}dataIn(e,t,n,o){this.info(e,`\u2192 ${t}`,n,o)}dataOut(e,t,n,o){this.info(e,`\u2190 ${t}`,n,o)}success(e,t,n,o){this.info(e,`\u2713 ${t}`,n,o)}failure(e,t,n,o){this.error(e,`\u2717 ${t}`,n,o)}},a=new ot});var N=require("fs"),tt=require("os"),de=require("path");w();var ne=y.transcriptsConfig(),Me=y.transcriptsState(),_n={version:1,schemas:{},watches:[],stateFile:Me};function Sn(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=b(r.path).replace(/\\/g,"/"),o=(0,de.join)((0,tt.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${o}/**/*.jsonl`}function Dt(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&Sn(r)}function b(r){return r&&(r.startsWith("~")?(0,de.join)((0,tt.homedir)(),r.slice(1)):r)}function pe(r=ne){let e=b(r);if(!(0,N.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=(0,N.readFileSync)(e,"utf-8"),n=JSON.parse(t);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=Me),n}function Ce(r=ne){let e=b(r),t=(0,de.dirname)(e);(0,N.existsSync)(t)||(0,N.mkdirSync)(t,{recursive:!0}),(0,N.writeFileSync)(e,JSON.stringify(_n,null,2))}var C=require("fs"),O=require("path");f();var F=require("fs"),Lt=require("path");f();function xt(r){try{if(!(0,F.existsSync)(r))return{offsets:{}};let e=(0,F.readFileSync)(r,"utf-8"),t=JSON.parse(e);return t.offsets?t:{offsets:{}}}catch(e){return a.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function Nt(r,e){try{let t=(0,Lt.dirname)(r);(0,F.existsSync)(t)||(0,F.mkdirSync)(t,{recursive:!0}),(0,F.writeFileSync)(r,JSON.stringify(e,null,2))}catch(t){a.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var Ee=X(require("path"),1);var T=X(require("path"),1),h=require("fs");var st=require("node:child_process");function be(r,e,t){return(0,st.spawn)(r,e??[],{windowsHide:!0,...t})}var hn=new Set([".cmd",".bat"]),yn=new Set([".exe",".com"]),as=new Set([...yn,...hn]);f();var k={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},B={SUCCESS:0,BLOCKING_ERROR:2};function J(r){return process.platform==="win32"?Math.round(r*k.WINDOWS_MULTIPLIER):r}var ve=require("fs"),it=require("path"),fe=require("os");ce();var Tn="security_alert",v=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(J(k.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:(0,it.join)((0,fe.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,it.join)((0,fe.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,fe.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0){try{if(!(0,ve.existsSync)(e)){let c=this.getAllDefaults();try{Te(e,c),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,l instanceof Error?l.message:String(l))}return t?this.applyEnvOverrides(c):c}let n=(0,ve.readFileSync)(e,"utf-8"),o=K(n),i=o;if(o.env&&typeof o.env=="object"){i=o.env;try{Te(e,i),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,c instanceof Error?c.message:String(c))}}if(i.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===Tn){i={...i,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{Te(e,i),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(c){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,c instanceof Error?c.message:String(c))}}let s={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))i[c]!==void 0&&(s[c]=i[c]);return t?this.applyEnvOverrides(s):s}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return t?this.applyEnvOverrides(o):o}}};w();w();var Re=null;function W(){return Re!==null||(Re=v.loadFromFile(re)),Re}var H=require("fs");f();var dt=require("child_process");var L=require("fs"),lt=X(require("path"),1);f();var wn=["CLAUDECODE_","CLAUDE_CODE_"],Mn=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Cn=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),bn=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...Cn]);function Ae(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(bn.has(t)){e[t]=n;continue}Mn.has(t)||wn.some(o=>t.startsWith(o))||(e[t]=n)}return e}w();var vn=5e3,Rn=1e3,An=y.supervisorRegistry();function P(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(a.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return a.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function ke(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!P(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var kn=5e3,Ut=new Map;function In(r){let e=(0,dt.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ae(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let t=e.stdout.trim();return t.length>0?t:null}return null}function On(r){let e=Ut.get(r);if(e&&Date.now()-e.capturedAtMs<kn)return e.token;let t=null;try{t=In(r)}catch(n){a.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return Ut.set(r,{token:t,capturedAtMs:Date.now()}),t}function Ft(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,L.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let o=e.slice(t+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return On(r);try{let e=(0,dt.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ae(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Ie(r){if(!r||!P(r.pid))return!1;if(!r.startToken)return!0;let e=Ft(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||a.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var ut=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=An){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,L.mkdirSync)(lt.default.dirname(this.registryPath),{recursive:!0}),!(0,L.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,L.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(t){t instanceof Error?a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&a.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&ct()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),o=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,o]of this.entries)P(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)ct();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;a.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(s=>s.pid)});let o=t.filter(s=>P(s.pid));for(let s of o)try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGTERM"):process.kill(s.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGTERM session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGTERM session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}await ke(o,vn);let i=o.filter(s=>P(s.pid));for(let s of i){a.warn("SYSTEM",`Session process PID ${s.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:s.pid,pgid:s.pgid,sessionId:n});try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGKILL"):process.kill(s.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGKILL session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGKILL session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}}if(i.length>0){let s=Date.now()+Rn;for(;Date.now()<s&&i.filter(l=>P(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let s of t)this.entries.delete(s.id),this.runtimeProcesses.delete(s.id);this.persist();for(let s of t)s.type==="sdk"&&ct();return a.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,L.mkdirSync)(lt.default.dirname(this.registryPath),{recursive:!0}),(0,L.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},at=null;function Oe(){return at||(at=new ut),at}var Dn=[];function ct(){let r=Dn.shift();r&&r()}var Ht=require("child_process"),oe=require("fs"),jt=require("util");f();w();var Pn=(0,jt.promisify)(Ht.execFile),Ln=y.workerPid();async function $t(r){let e=r.currentPid??process.pid,t=r.pidFilePath??Ln,n=r.registry.getAll(),o=[...n].filter(s=>s.pid!==e).sort((s,c)=>Date.parse(c.startedAt)-Date.parse(s.startedAt));for(let s of o){if(!P(s.pid)){r.registry.unregister(s.id);continue}try{await Wt(s,"SIGTERM")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}}await ke(o,5e3);let i=o.filter(s=>P(s.pid));for(let s of i)try{await Wt(s,"SIGKILL")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}await ke(i,1e3);for(let s of o)r.registry.unregister(s.id);for(let s of n.filter(c=>c.pid===e))r.registry.unregister(s.id);Gt(t,e),r.registry.pruneDeadEntries()}function Gt(r,e,t=!1){if(!(0,oe.existsSync)(r))return;let n=null;try{let s=JSON.parse((0,oe.readFileSync)(r,"utf-8"));n=typeof s.pid=="number"?s.pid:null}catch(s){a.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:s instanceof Error?s.message:String(s)});return}let o=e!==null&&n===e,i=n===null||!P(n);if(!o&&!(t&&i)){a.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,oe.rmSync)(r,{force:!0})}catch(s){s instanceof Error?a.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},s):a.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(s)})}}async function Wt(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}try{process.kill(t,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let o=["/PID",String(t),"/T"];e==="SIGKILL"&&o.push("/F"),await Pn("taskkill",o,{timeout:k.POWERSHELL_COMMAND,windowsHide:!0})}f();var Yt=3e4,se=null;function xn(){let e=Oe().pruneDeadEntries();e>0&&a.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Kt(){se===null&&(se=setInterval(xn,Yt),se.unref(),a.debug("SYSTEM","Health checker started",{intervalMs:Yt}))}function Bt(){se!==null&&(clearInterval(se),se=null,a.debug("SYSTEM","Health checker stopped"))}w();var pt=y.workerPid(),ft=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),De({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Kt()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){a.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,a.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?a.error("SYSTEM","Error during shutdown",{},o):a.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?a.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):a.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{a.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Bt(),this.stopPromise=$t({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Ns=new ft(Oe());function Jt(){if(!(0,H.existsSync)(pt))return null;let r;try{r=JSON.parse((0,H.readFileSync)(pt,"utf-8"))}catch{return null}return r!==null&&Ie(r)?r:null}function De(r={}){let e=r.pidFilePath??pt;if(!(0,H.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,H.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,H.rmSync)(e,{force:!0}),"invalid"}return Ie(t)&&t?((r.logAlive??!0)&&a.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(a.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,H.rmSync)(e,{force:!0}),"stale")}ye();var mt=require("path"),Le=require("fs"),qt=require("crypto");w();var Pe=require("fs");ce();function Vt(r,e){if(!(0,Pe.existsSync)(r))return e;try{return K((0,Pe.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}f();var Xt="telemetry.json";function Nn(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Un(r,e){if(Nn(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.CLAUDE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function zt(r,e){return Un(r,e).enabled}function Fn(){return(0,mt.join)(te(),Xt)}function gt(){let r;try{r=Vt(Fn(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function Wn(r){let e=te();(0,Le.mkdirSync)(e,{recursive:!0}),(0,Le.writeFileSync)((0,mt.join)(e,Xt),JSON.stringify(r,null,2)+`
`)}function Qt(){let r=gt();if(r?.installId)return r.installId;let e=(0,qt.randomUUID)();return Wn({installId:e,decidedAt:""}),e}var Hn=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),Zt=200;function jn(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Hn.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>Zt?n.slice(0,Zt):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function er(r){let e={};try{jn(r,e)}catch{}return e}var Et=X(require("os"),1);f();var $n="13.13.1",Gn="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Yn="https://us.i.posthog.com";function tr(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Gn}function rr(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Yn}var Kn=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function nr(r){let e={};for(let t of Kn)r[t]!==void 0&&(e[t]=r[t]);return e}function Bn(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Et.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function or(){return{version:$n,os:process.platform,os_version:Et.default.release(),is_wsl:Bn(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var Jn=2e3;async function sr(r,e,t){try{if(!zt(process.env,gt()))return;let n=er({...or(),...e??{}});if(t?.person?n.$set=nr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
`);return}let o=tr(),i=new AbortController,s=setTimeout(()=>i.abort(),Jn);try{await Vn(o,r,n,i.signal)}finally{clearTimeout(s)}}catch{}}async function Vn(r,e,t,n){await fetch(`${rr()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:Qt(),properties:t}),signal:n})}var z=X(require("path"),1),ar=require("os"),j=require("fs"),St=require("child_process");f();f();f();w();var mi=y.dataDir(),gi=y.workerPid();function ir(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Xn(r,e){let t=e==="win32"?`where ${r}`:`which ${r}`,n;try{n=(0,St.execSync)(t,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},i):a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},new Error(String(i))),null}return n.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}var _t;function cr(r={}){let e=Object.keys(r).length===0;if(e&&_t!==void 0)return _t;let t=zn(r);return e&&t!==null&&(_t=t),t}function zn(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(ir(t))return t;let n=r.env??process.env,o=r.homeDirectory??(0,ar.homedir)(),i=r.pathExists??j.existsSync,s=r.lookupInPath??Xn,c=e==="win32"?[n.BUN,n.BUN_PATH,z.default.join(o,".bun","bin","bun.exe"),z.default.join(o,".bun","bin","bun"),n.USERPROFILE?z.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?z.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?z.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,z.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of c){let d=l?.trim();if(d&&(ir(d)&&i(d)||d.toLowerCase()==="bun"))return d}return s("bun",e)}f();w();function Qn(){return v.loadFromFile(re).CLAUDE_MEM_WORKER_HOST}function Zn(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}async function eo(r,e,t="GET"){let n=await fetch(`http://${Zn(Qn())}:${r}${e}`,{method:t}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function to(r){try{let e=await eo(r,"/api/health");return e.ok?JSON.parse(e.body).version:null}catch{return a.debug("SYSTEM","Could not fetch worker version",{}),null}}async function lr(r,e){let t=e??"unknown",n=await to(r);return!n||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:n}:{matches:t===n,pluginVersion:t,workerVersion:n}}f();var xe=require("path"),R=require("fs");w();f();var ro=9e4;function ur(){return(0,xe.join)(te(),"spawn.lock")}function dr(){let r=ur(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,R.mkdirSync)((0,xe.dirname)(r),{recursive:!0}),(0,R.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),i=o.code;if(i!=="EEXIST")return a.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},o),!0;if(t>0)return!1;let s;try{s=(0,R.statSync)(r).mtimeMs}catch{continue}if(Date.now()-s<=ro)return!1;let c;try{c=(0,R.statSync)(r).mtimeMs}catch{continue}if(c!==s)return!1;try{(0,R.unlinkSync)(r)}catch{return!1}}return!1}function pr(){let r=ur();try{if(JSON.parse((0,R.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,R.unlinkSync)(r)}catch{}}function yr(r,e,t){let n=process.env[r];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=t.min&&o<=t.max)return o;a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var je=yr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",J(k.HEALTH_CHECK),{min:500,max:3e5}),no=yr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",J(k.HOOK_READINESS_WAIT),{min:0,max:3e5}),oo={min:500,max:3e5};async function yt(r,e={},t){try{return await fetch(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}var Ne=null,Ue=null,Fe=null,We=null;function so(){return T.default.join(v.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Tt(){return Fe!==null||(Fe=v.loadFromFile(so())),Fe}function fr(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function io(r,e,t){let n=process.env[r];if(n!==void 0){let s=fr(n,t);return s!==null?s:(a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let o=Tt()[r],i=fr(o,t);return i!==null?i:(a.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:o,min:t.min,max:t.max}),e)}function me(){if(Ne!==null)return Ne;let r=Tt();return Ne=parseInt(r.CLAUDE_MEM_WORKER_PORT,10),Ne}function ao(){return Ue!==null||(Ue=Tt().CLAUDE_MEM_WORKER_HOST),Ue}function co(){return We!==null||(We=io("CLAUDE_MEM_API_TIMEOUT_MS",J(k.API_REQUEST),oo)),We}function lo(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}function uo(r){return`http://${lo(ao())}:${me()}${r}`}function $(r,e={}){let t=e.method??"GET",n=e.timeoutMs??co(),o=uo(r),i={method:t};return e.headers&&(i.headers=e.headers),e.body&&(i.body=e.body),n>0?yt(o,i,n):fetch(o,i)}async function po(){return(await $("/api/health",{timeoutMs:je})).ok}async function mr(){return(await $("/api/readiness",{timeoutMs:je})).ok}function Tr(r){let e=(0,h.existsSync)(T.default.join(r,"plugin","scripts"))?T.default.join(r,"plugin"):r;return T.default.join(e,"scripts","worker-service.cjs")}function fo(r,e){let t=E=>{let g=E.split("-")[0].split(".");return[parseInt(g[0],10)||0,parseInt(g[1],10)||0,parseInt(g[2],10)||0]},[n,o,i]=t(r),[s,c,l]=t(e);if(s!==n)return s-n;if(c!==o)return c-o;if(l!==i)return l-i;let d=r.includes("-")?1:0,u=e.includes("-")?1:0;return d!==u?d-u:r<e?1:r>e?-1:0}function mo(r=T.default.join(T.default.dirname(T.default.dirname(we)),"cache","thedotmack","claude-mem")){try{return(0,h.readdirSync)(r).filter(e=>/^\d/.test(e)).map(e=>T.default.join(r,e)).filter(e=>{try{if(!(0,h.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,h.existsSync)(T.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:Tr(e),version:T.default.basename(e)}))}catch{return[]}}function gr(r){try{let e=JSON.parse((0,h.readFileSync)(r,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let t=e.code;return t!=="ENOENT"&&a.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:r,code:t}),null}}function go(){let r=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(r){if((0,h.existsSync)(r))return{scriptPath:r,version:null};a.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:r})}let e=[...mo(),{scriptPath:Tr(T.default.join(we,"plugin")),version:gr(T.default.join(we,"package.json"))},{scriptPath:T.default.join(process.cwd(),"plugin","scripts","worker-service.cjs"),version:gr(T.default.join(process.cwd(),"package.json"))}];return Eo(e)}function Eo(r){let e=r.filter(t=>(0,h.existsSync)(t.scriptPath));return e.length===0?null:(e.sort((t,n)=>t.version===null&&n.version===null?0:t.version===null?1:n.version===null?-1:fo(t.version,n.version)),e[0])}async function _o(r){let e=r.backoffMs;for(let t=1;t<=r.attempts;t++){if(await wr())return!0;t<r.attempts&&(await new Promise(n=>setTimeout(n,e)),e*=2)}return!1}async function Er(r=no){if(r<=0)try{return await mr()}catch(t){let n=t instanceof Error?t:new Error(String(t));return a.debug("SYSTEM","Worker readiness check threw",{},n),!1}let e=Date.now();for(;Date.now()-e<r;){try{if(await mr())return!0}catch(n){a.debug("SYSTEM","Worker readiness check threw",{error:n instanceof Error?n.message:String(n)})}let t=r-(Date.now()-e);if(t<=0)break;await new Promise(n=>setTimeout(n,Math.min(250,t)))}return!1}async function So(){try{let e=await(await $("/api/health",{timeoutMs:je})).json();return typeof e.version=="string"?e.version:null}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.debug("SYSTEM","Worker health-version fetch failed",{},e),null}}async function ho(r=5e3){let e=Date.now();for(;;){try{await $("/api/health",{timeoutMs:je})}catch{return!0}if(Date.now()-e>=r)return!1;await new Promise(t=>setTimeout(t,200))}}async function _r(r){let e=await So();e!==null&&e!==r&&a.warn("SYSTEM","Worker is ready but still reports a stale version; not recycling again in this hook invocation (one recycle per hook event)",{pluginVersion:r,workerVersion:e})}async function wr(){let r;try{r=await po()}catch(t){return a.debug("SYSTEM","Worker health check threw",{error:t instanceof Error?t.message:String(t)}),!1}if(!r)return!1;let e=De({logAlive:!1});return e==="missing"||e==="alive"}async function $e(){let r=go(),e=null;if(await wr()){let{matches:s,pluginVersion:c,workerVersion:l}=await lr(me(),r?.version??null);if(c!=="unknown"&&(e=c),s)return await Er()?(e!==null&&await _r(e),!0):(a.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);a.info("SYSTEM","Worker version mismatch \u2014 killing stale worker",{pluginVersion:c,workerVersion:l});let d=Jt();if(d===null||d.port!==me())return a.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the claude-mem worker process manually",{port:me(),pidFilePid:d?.pid??null,pidFilePort:d?.port??null}),!1;try{process.kill(d.pid,"SIGKILL")}catch(u){if(u.code!=="ESRCH")return a.error("SYSTEM","Could not kill stale worker",{pid:d.pid,port:d.port},u instanceof Error?u:new Error(String(u))),!1}if(!await ho())return a.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:d.pid,port:me()}),!1}let t=cr(),n=r?.scriptPath??null;if(!t)return a.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!n)return a.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let o=dr();try{if(o){a.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:t,scriptPath:n});try{be(t,[n,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(c){return c instanceof Error?a.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:t,scriptPath:n},c):a.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:t,scriptPath:n,error:String(c)}),!1}}else a.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await _o({attempts:6,backoffMs:500}))return a.warn("SYSTEM",o?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{o&&pr()}return await Er()?(e!==null&&await _r(e),!0):(a.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var He=null;async function yo(){return He!==null||(He=await $e()),He}var To=3;function Mr(){return T.default.join(S,"state")}function Cr(){return T.default.join(Mr(),"hook-failures.json")}function wo(r){let e=JSON.parse(r);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}function br(){try{return wo((0,h.readFileSync)(Cr(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function vr(r){let e=Mr(),t=Cr(),n=`${t}.tmp`;try{(0,h.existsSync)(e)||(0,h.mkdirSync)(e,{recursive:!0}),(0,h.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,h.renameSync)(n,t)}catch(o){a.debug("SYSTEM","Failed to persist hook-failure counter",{error:o instanceof Error?o.message:String(o)})}}function Mo(){try{let e=W().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return To}var Sr=null;async function Co(){let e={consecutiveFailures:br().consecutiveFailures+1,lastFailureAt:Date.now()};vr(e);let t=Mo();return e.consecutiveFailures>=t&&(e.consecutiveFailures===t&&await sr("hook_failed",{...Sr!==null?{hook_type:Sr}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),At(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function hr(){br().consecutiveFailures!==0&&vr({consecutiveFailures:0,lastFailureAt:0})}var ht=Symbol.for("claude-mem/worker-fallback");function Ge(r){return typeof r=="object"&&r!==null&&r[ht]===!0}async function Ye(r,e,t,n={}){if(!await yo())return await Co(),{continue:!0,reason:"worker_unreachable",[ht]:!0};let i={method:e};t!==void 0&&(i.headers={"Content-Type":"application/json"},i.body=JSON.stringify(t)),n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs);let s=await $(r,i);if(!s.ok){let l=await s.text().catch(()=>"");if(hr(),s.status===429||s.status>=500)return a.warn("SYSTEM",`Worker API ${e} ${r} returned ${s.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${s.status}`,[ht]:!0};let d=l;try{d=JSON.parse(l)}catch{}return d}hr();let c=await s.text();if(c.length!==0)try{return JSON.parse(c)}catch{return c}}var Ar=require("os"),kr=X(require("path"),1),Ir=require("child_process");f();var Ke=require("fs"),ie=X(require("path"),1);f();var ge={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Rr(r){let e=ie.default.join(r,".git"),t;try{t=(0,Ke.statSync)(e)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&a.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),ge}if(!t.isFile())return ge;let n;try{n=(0,Ke.readFileSync)(e,"utf-8").trim()}catch(u){return a.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),ge}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return ge;let s=ie.default.resolve(ie.default.dirname(e),o[1]).match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!s)return ge;let c=s[1],l=ie.default.basename(r),d=ie.default.basename(c);return{isWorktree:!0,worktreeName:l,parentRepoPath:c,parentProjectName:d}}function Or(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,Ar.homedir)()):r}function Dr(r){try{return(0,Ir.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:r},t),null}}function bo(r){if(!r||r.trim()==="")return a.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Or(r),n=Dr(e)??e,o=kr.default.basename(n);if(o===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let l=`drive-${s[1].toUpperCase()}`;return a.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:l}),l}}return a.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return o}function Q(r){let e=bo(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Or(r),n=Rr(Dr(t)??t);if(n.isWorktree&&n.parentProjectName){let o=`${n.parentProjectName}/${e}`;return{primary:o,parent:n.parentProjectName,isWorktree:!0,allProjects:[n.parentProjectName,o]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}f();var Z=require("path");var Pr=require("os"),Lr=require("path");f();function vo(r){let e=r.startsWith("~")?(0,Pr.homedir)()+r.slice(1):r;e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function Be(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,Lr.basename)(t),o=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of o)try{let s=vo(i);if(s.test(t)||s.test(n))return!0}catch(s){a.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:s instanceof Error?s.message:String(s)});continue}return!1}w();function Ro(r,e){let t=(0,Z.normalize)(r),n=(0,Z.normalize)(e);if(t===n)return!0;let o=(0,Z.relative)(n,t);return o.length>0&&!o.startsWith("..")&&!(0,Z.isAbsolute)(o)}function Je(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(Ro(r,et))return!1;let e=W();return!Be(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var xr="claude";function Ao(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function x(r){if(!r)return xr;let e=Ao(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:xr}f();var Fr=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Nr=new RegExp(`<(${Fr.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Ur=100;function ko(r){let e=Object.fromEntries(Fr.map(o=>[o,0]));Nr.lastIndex=0;let t=0,n=r.replace(Nr,(o,i)=>(e[i]=(e[i]??0)+1,t+=1,""));return t>Ur&&a.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:Ur,contentLength:r.length}),{stripped:n.trim(),counts:e}}function wt(r){return ko(r).stripped}var Io=["task-notification"],Oo=new RegExp(`^\\s*<(${Io.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Do=256*1024;function Wr(r){return!r||r.length>Do?!1:Oo.test(r)}f();var Po=J(k.API_REQUEST),G=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ve=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Lo(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Po}async startSession(e){let t=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new G("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new G("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:t,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Mt(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Mt(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Mt(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n){if(!this.apiKey||!this.apiKey.trim())throw new G("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${t}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let s;try{s=await yt(o,i,this.timeoutMs)}catch(l){let d=l instanceof Error?l.message:String(l),u=/timed out|timeout/i.test(d);throw new G(u?"timeout":"transport",`Server ${e} ${t} failed: ${d}`,{cause:l})}if(!s.ok){let l=await s.text().catch(()=>"");throw new G("http_error",`Server ${e} ${t} returned ${s.status}: ${xo(l,200)}`,{status:s.status})}let c=await s.text();if(!c||c.length===0)return{};try{return JSON.parse(c)}catch(l){let d=l instanceof Error?l:new Error(String(l));throw new G("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:d})}}};function Hr(r){return r instanceof G}function Lo(r){return r.replace(/\/+$/,"")}function Mt(r){return typeof r=="string"?x(r):null}function xo(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function No(){let e=(W().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Uo(){let r=W(),e=(...s)=>{for(let c of s){let l=(c??"").trim();if(l.length>0)return l}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return a.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return a.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return a.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new Ve(i),projectId:o,serverBaseUrl:t}}function jr(){if(No()!=="server")return{runtime:"worker"};let r=Uo();return r||{runtime:"worker"}}function $r(r,e){a.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var Fo={executeWithWorkerFallback:Ye,isWorkerFallback:Ge,loadFromFileOnce:W,resolveRuntimeContext:jr,logServerFallback:$r,shouldTrackProject:Je},V=Fo;var Gr={async execute(r){let{sessionId:e,prompt:t}=r,n=r.cwd??process.cwd();if(!e)return a.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:B.SUCCESS};if(!V.shouldTrackProject(n))return a.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};if(t&&Wr(t))return a.debug("HOOK","session-init: skipping internal protocol payload",{preview:t.slice(0,80)}),{continue:!0,suppressOutput:!0};let o=!t||!t.trim()?"[media prompt]":t,i=Q(n).primary,s=x(r.platform),c=V.loadFromFileOnce(),l=String(c.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",d=V.resolveRuntimeContext();if(d.runtime==="server")try{return await Wo(d,r,e,s,i,o),{continue:!0,suppressOutput:!0}}catch(_){if(Hr(_)&&_.isFallbackEligible())V.logServerFallback(_.kind,{status:_.status,message:_.message,route:"/v1/sessions/start"});else return a.error("HOOK","Server session-start failed (non-recoverable)",{error:_ instanceof Error?_.message:String(_)}),{continue:!0,suppressOutput:!0,exitCode:B.SUCCESS}}a.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:i});let u=await V.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:i,prompt:o,platformSource:s});if(V.isWorkerFallback(u))return{continue:!0,suppressOutput:!0,exitCode:B.SUCCESS};if(typeof u?.sessionDbId!="number")return a.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:i}),{continue:!0,suppressOutput:!0,exitCode:B.SUCCESS};let E=u.sessionDbId,g=u.promptNumber;if(a.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:E,promptNumber:g,skipped:u.skipped,contextInjected:u.contextInjected}),a.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${g} | sessionDbId=${E}`),u.skipped&&u.reason==="private")return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${E} | promptNumber=${g} | skipped=true | reason=private`,{sessionId:E}),{continue:!0,suppressOutput:!0};let M="";if(l&&o&&o.length>=20&&o!=="[media prompt]"){let _=c.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",Y=await V.executeWithWorkerFallback("/api/context/semantic","POST",{q:o,project:i,limit:_,platformSource:s});!V.isWorkerFallback(Y)&&Y?.context&&(a.debug("HOOK",`Semantic injection: ${Y.count} observations for prompt`,{sessionId:E,count:Y.count}),M=Y.context)}return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${E} | promptNumber=${g} | project=${i}`,{sessionId:E}),M?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:M}}:{continue:!0,suppressOutput:!0}}};async function Wo(r,e,t,n,o,i){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:o,prompt:i}}),a.info("HOOK","session-init: server session started",{contentSessionId:t,project:o})}f();var Yr={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:o}=r,i=x(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(a.dataIn("HOOK",`FileEdit: ${n}`,{editCount:o?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!Je(t))return a.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:B.SUCCESS};let s=await Ye("/api/sessions/observations","POST",{contentSessionId:e,platformSource:i,tool_name:"write_file",tool_input:{filePath:n,edits:o},tool_response:{success:!0},cwd:t});return Ge(s)?{continue:!0,suppressOutput:!0,exitCode:B.SUCCESS}:(a.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0})}};w();f();var I=require("fs"),qe=require("path");f();f();w();var Ya=y.settings();function Kr(r,e){let t="<claude-mem-context>",n="</claude-mem-context>";if(!r)return`${t}
${e}
${n}`;let o=r.indexOf(t),i=r.indexOf(n);return o!==-1&&i!==-1?r.substring(0,o)+`${t}
${e}
${n}`+r.substring(i+n.length):r+`
${t}
${e}
${n}`}f();function Br(r,e){if(!r)return;let t=(0,qe.resolve)(r);if(t.includes("/.git/")||t.includes("\\.git\\")||t.endsWith("/.git")||t.endsWith("\\.git"))return;let n=(0,qe.dirname)(r);(0,I.existsSync)(n)||(0,I.mkdirSync)(n,{recursive:!0});let o="";(0,I.existsSync)(r)&&(o=(0,I.readFileSync)(r,"utf-8"));let i=`# Memory Context
${e}`,s=Kr(o,i),c=`${r}.tmp`;try{(0,I.writeFileSync)(c,s),(0,I.renameSync)(c,r)}catch(l){a.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:r},l instanceof Error?l:new Error(String(l)))}}f();function Ho(r){let e=r.trim().replace(/^\$\.?/,"");if(!e)return[];let t=[],n=e.split(".");for(let o of n){let i=/([^[\]]+)|\[(\d+)\]/g,s;for(;(s=i.exec(o))!==null;)s[1]?t.push(s[1]):s[2]&&t.push(parseInt(s[2],10))}return t}function Ct(r,e){if(!e)return;let t=Ho(e),n=r;for(let o of t){if(n==null)return;n=n[o]}return n}function Jr(r){return r==null||r===""}function Vr(r,e){if(r.startsWith("$watch.")){let t=r.slice(7);return e.watch[t]}if(r.startsWith("$schema.")){let t=r.slice(8);return e.schema[t]}if(r.startsWith("$session.")){let t=r.slice(9);return e.session?e.session[t]:void 0}if(r==="$cwd")return e.watch.workspace;if(r==="$project")return e.watch.project}function ae(r,e,t){if(r!==void 0){if(typeof r=="string"){let n=Vr(r,t);return n!==void 0?n:Ct(e,r)}if(r.coalesce&&Array.isArray(r.coalesce))for(let n of r.coalesce){let o=ae(n,e,t);if(!Jr(o))return o}if(r.path){let n=Vr(r.path,t);if(n!==void 0)return n;let o=Ct(e,r.path);if(!Jr(o))return o}if(r.value!==void 0)return r.value;if(r.default!==void 0)return r.default}}function qr(r,e,t){let n={};if(!r)return n;for(let[o,i]of Object.entries(r))n[o]=ae(i,e,t);return n}function Xr(r,e,t){if(!e)return!0;let n=e.path||t.eventTypePath||"type",o=n?Ct(r,n):void 0,i=o==null||o==="";if(e.exists!==void 0&&(e.exists&&i||!e.exists&&!i)||e.equals!==void 0&&o!==e.equals||e.not_equals!==void 0&&o===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(o)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(o)||e.contains!==void 0&&(typeof o!="string"||!o.includes(e.contains))||e.not_contains!==void 0&&typeof o=="string"&&o.includes(e.not_contains))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(o??"")))return!1}catch(s){return a.debug("WORKER","Invalid regex in match rule",{regex:e.regex},s instanceof Error?s:void 0),!1}return!0}f();w();f();var Xe=class{static checkUserPromptPrivacy(e,t,n,o,i,s){let c=e.getUserPrompt(t,n,i);return c===null?(a.warn("HOOK",`${o}: no user_prompts row for prompt #${n} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:i,contentSessionId:t,promptNumber:n,...s}),{allow:!0,prompt:""}):c.trim()===""?(a.debug("HOOK",`Skipping ${o} - user prompt was entirely private`,{sessionId:i,promptNumber:n,...s}),{allow:!1,reason:"private"}):{allow:!0,prompt:c}}};var zr=null;function jo(){if(!zr)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return zr}async function Qr(r){let{sessionManager:e,dbManager:t,eventBroadcaster:n,ensureGeneratorRunning:o}=jo(),i=x(r.platformSource),s=typeof r.cwd=="string"?r.cwd:"",c=s.trim()?Q(s).primary:"",l=v.loadFromFile(re);if(s&&Be(s,l.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(new Set(l.CLAUDE_MEM_SKIP_TOOLS.split(",").map(A=>A.trim()).filter(Boolean)).has(r.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(r.toolName)&&r.toolInput&&typeof r.toolInput=="object"){let A=r.toolInput,q=A.file_path||A.notebook_path;if(q&&q.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let E=t.getSessionStore(),g,M;try{g=E.createSDKSession(r.contentSessionId,c,"",void 0,i),M=E.getPromptNumberFromUserPrompts(r.contentSessionId,g)}catch(A){let q=A instanceof Error?A.message:String(A);return a.error("INGEST","Observation session resolution failed",{contentSessionId:r.contentSessionId,toolName:r.toolName},A instanceof Error?A:new Error(q)),{ok:!1,reason:q,status:500}}if(!Xe.checkUserPromptPrivacy(E,r.contentSessionId,M,"observation",g,{tool_name:r.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let Y=r.toolInput!==void 0?wt(JSON.stringify(r.toolInput)):"{}",_e=r.toolResponse!==void 0?wt(JSON.stringify(r.toolResponse)):"{}";return await e.queueObservation(g,{tool_name:r.toolName,tool_input:Y,tool_response:_e,prompt_number:M,cwd:s||(a.error("INGEST","Missing cwd when ingesting observation",{sessionId:g,toolName:r.toolName}),""),agentId:typeof r.agentId=="string"?r.agentId:void 0,agentType:typeof r.agentType=="string"?r.agentType:void 0,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0}),await o?.(g,"observation"),n.broadcastObservationQueued(g),{ok:!0,sessionDbId:g}}var ze=class{sessions=new Map;async processEntry(e,t,n,o){for(let i of n.events)Xr(e,i.match,n)&&await this.handleEvent(e,t,n,i,o??void 0)}getSessionKey(e,t){return`${e.name}:${t}`}getOrCreateSession(e,t){let n=this.getSessionKey(e,t),o=this.sessions.get(n);return o||(o={sessionId:t,platformSource:x(e.name)},this.sessions.set(n,o)),o}resolveSessionId(e,t,n,o,i){let s={watch:t,schema:n},c=o.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),l=ae(c,e,s);return typeof l=="string"&&l.trim()?l:typeof l=="number"?String(l):i&&i.trim()?i:null}resolveCwd(e,t,n,o,i){let s={watch:t,schema:n,session:i},c=o.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),l=ae(c,e,s);return typeof l=="string"&&l.trim()?l:t.workspace?t.workspace:i.cwd}resolveProject(e,t,n,o,i){let s={watch:t,schema:n,session:i},c=o.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),l=ae(c,e,s);return typeof l=="string"&&l.trim()?l:t.project?t.project:i.cwd?Q(i.cwd).primary:i.project}async handleEvent(e,t,n,o,i){let s=this.resolveSessionId(e,t,n,o,i);if(!s){a.debug("TRANSCRIPT","Skipping event without sessionId",{event:o.name,watch:t.name});return}let c=this.getOrCreateSession(t,s),l=this.resolveCwd(e,t,n,o,c);l&&(c.cwd=l);let d=this.resolveProject(e,t,n,o,c);d&&(c.project=d);let u=qr(o.fields,e,{watch:t,schema:n,session:c});switch(o.action){case"session_context":this.applySessionContext(c,u);break;case"session_init":await this.handleSessionInit(c,u),t.context?.updateOn?.includes("session_start")&&await this.updateContext(c,t);break;case"user_message":typeof u.message=="string"&&(c.lastUserMessage=u.message),typeof u.prompt=="string"&&(c.lastUserMessage=u.prompt);break;case"assistant_message":typeof u.message=="string"&&(c.lastAssistantMessage=u.message);break;case"tool_use":await this.handleToolUse(c,u);break;case"tool_result":await this.handleToolResult(c,u);break;case"observation":await this.sendObservation(c,u);break;case"file_edit":await this.sendFileEdit(c,u);break;case"session_end":await this.handleSessionEnd(c,t);break;default:break}}applySessionContext(e,t){let n=typeof t.cwd=="string"?t.cwd:void 0,o=typeof t.project=="string"?t.project:void 0;n&&(e.cwd=n),o&&(e.project=o)}async handleSessionInit(e,t){let n=typeof t.prompt=="string"?t.prompt:"",o=e.cwd??process.cwd();n&&(e.lastUserMessage=n),await Gr.execute({sessionId:e.sessionId,cwd:o,prompt:n,platform:e.platformSource})}async handleToolUse(e,t){let n=typeof t.toolId=="string"?t.toolId:void 0,o=typeof t.toolName=="string"?t.toolName:void 0,i=this.maybeParseJson(t.toolInput),s=this.maybeParseJson(t.toolResponse);if(o==="apply_patch"&&typeof i=="string"){let c=this.parseApplyPatchFiles(i);for(let l of c)await this.sendFileEdit(e,{filePath:l,edits:[{type:"apply_patch",patch:i}]})}o&&s!==void 0?await this.sendObservation(e,{toolName:o,toolInput:i,toolResponse:s,toolUseId:n}):o&&n&&(e.pendingTools||(e.pendingTools=new Map),e.pendingTools.set(n,{toolName:o,toolInput:i}))}async handleToolResult(e,t){let n=typeof t.toolId=="string"?t.toolId:void 0,o=typeof t.toolName=="string"?t.toolName:void 0,i=this.maybeParseJson(t.toolResponse),s=this.maybeParseJson(t.toolInput);if(n&&e.pendingTools){let c=e.pendingTools.get(n);c&&(o||(o=c.toolName),s===void 0&&(s=c.toolInput),e.pendingTools.delete(n))}o?await this.sendObservation(e,{toolName:o,toolInput:s,toolResponse:i,toolUseId:n}):a.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:n})}async sendObservation(e,t){let n=typeof t.toolName=="string"?t.toolName:void 0;if(!n)return;let o=await Qr({contentSessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:n,toolInput:this.maybeParseJson(t.toolInput),toolResponse:this.maybeParseJson(t.toolResponse),platformSource:e.platformSource,toolUseId:typeof t.toolUseId=="string"?t.toolUseId:void 0});if(!o.ok)throw new Error(`ingestObservation failed: ${o.reason}`)}async sendFileEdit(e,t){let n=typeof t.filePath=="string"?t.filePath:void 0;n&&await Yr.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:n,edits:Array.isArray(t.edits)?t.edits:void 0,platform:e.platformSource})}maybeParseJson(e){if(typeof e!="string")return e;let t=e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return e;try{return JSON.parse(t)}catch(n){return a.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:t.slice(0,120)},n instanceof Error?n:void 0),e}}parseApplyPatchFiles(e){let t=[],n=e.split(`
`);for(let o of n){let i=o.trim();if(i.startsWith("*** Update File: "))t.push(i.replace("*** Update File: ","").trim());else if(i.startsWith("*** Add File: "))t.push(i.replace("*** Add File: ","").trim());else if(i.startsWith("*** Delete File: "))t.push(i.replace("*** Delete File: ","").trim());else if(i.startsWith("*** Move to: "))t.push(i.replace("*** Move to: ","").trim());else if(i.startsWith("+++ ")){let s=i.replace("+++ ","").replace(/^b\//,"").trim();s&&s!=="/dev/null"&&t.push(s)}}return Array.from(new Set(t))}async handleSessionEnd(e,t){await this.queueSummary(e),await this.updateContext(e,t),e.pendingTools?.clear();let n=this.getSessionKey(t,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(!await $e())return;let n=e.lastAssistantMessage??"",o=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n,platformSource:e.platformSource});try{await $("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:o})}catch(i){a.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,t){if(!t.context||t.context.mode!=="agents"||Dt(t)||!await $e())return;let o=e.cwd??t.workspace;if(!o)return;let s=Q(o).allProjects.join(","),c=`/api/context/inject?projects=${encodeURIComponent(s)}&platformSource=${encodeURIComponent(e.platformSource)}`,l=b(t.context.path??`${o}/AGENTS.md`),d=Ee.default.resolve(l),u=[Ee.default.resolve(o),Ee.default.resolve(S)];if(!u.some(_=>d.startsWith(_+Ee.default.sep)||d===_)){a.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:t.context.path,resolved:d,allowedRoots:u});return}let g;try{g=await $(c)}catch(_){a.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:_ instanceof Error?_.message:String(_)});return}if(!g.ok)return;let M=(await g.text()).trim();M&&(Br(l,M),a.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:l,watch:t.name}))}};var bt=class{constructor(e,t,n,o){this.filePath=e;this.onLine=n;this.onOffset=o;this.tailState={offset:t,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,C.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,C.existsSync)(this.filePath))return;let e=0;try{e=(0,C.statSync)(this.filePath).size}catch(s){a.debug("WORKER","Failed to stat transcript file",{file:this.filePath},s instanceof Error?s:void 0);return}if(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let t=(0,C.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),n="";for await(let s of t)n+=s;this.tailState.offset=e,this.onOffset(this.tailState.offset);let i=(this.tailState.partial+n).split(`
`);this.tailState.partial=i.pop()??"";for(let s of i){let c=s.trim();c&&await this.onLine(c)}}},Qe=class{constructor(e,t){this.config=e;this.statePath=t;this.state=xt(t)}config;statePath;processor=new ze;tailers=new Map;state;rootWatchers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[]}async setupWatch(e){let t=this.resolveSchema(e);if(!t){a.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=b(e.path),o=this.resolveWatchFiles(n);for(let s of o)await this.addTailer(s,e,t);let i=this.deepestNonGlobAncestor(n);if(!i||!(0,C.existsSync)(i)){a.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:i});return}try{let s=(0,C.watch)(i,{recursive:!0,persistent:!0},(c,l)=>{this.handleRootWatchEvent(i,n,e,t,l)});this.rootWatchers.push(s),a.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:i})}catch(s){a.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:i},s instanceof Error?s:void 0)}}handleRootWatchEvent(e,t,n,o,i){if(!i)return;let s=(0,O.resolve)(e,i).replace(/\\/g,"/"),c=this.tailers.get(s);if(c){c.poke();return}let l=this.resolveWatchFiles(t);for(let d of l)this.tailers.has(d)||this.addTailer(d,n,o)}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,C.existsSync)(e))try{return(0,C.statSync)(e).isDirectory()?e:(0,O.resolve)(e,"..")}catch(o){return a.debug("TRANSCRIPT","Failed to stat watch path ancestor, falling back to parent directory",{path:e},o instanceof Error?o:new Error(String(o))),(0,O.resolve)(e,"..")}return e}let t=e.split(/[/\\]/),n=[];for(let o of t){if(/[*?[\]{}()]/.test(o))break;n.push(o)}return n.length===0||n.length===1&&n[0]===""?"":n.join(O.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return this.scanGlob(this.normalizeGlobPattern(e));if((0,C.existsSync)(e))try{if((0,C.statSync)(e).isDirectory()){let n=(0,O.join)(e,"**","*.jsonl");return this.scanGlob(this.normalizeGlobPattern(n))}return[e]}catch(t){return a.debug("WORKER","Failed to stat watch path",{path:e},t instanceof Error?t:void 0),[]}return[]}scanGlob(e){return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0}))}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,t,n){if(this.tailers.has(e))return;let o=this.extractSessionIdFromPath(e),i=this.state.offsets[e]??0;if(i===0&&t.startAtEnd)try{i=(0,C.statSync)(e).size}catch(c){a.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},c instanceof Error?c:void 0),i=0}let s=new bt(e,i,async c=>{await this.handleLine(c,t,n,e,o)},c=>{this.state.offsets[e]=c,Nt(this.statePath,this.state)});s.start(),this.tailers.set(e,s),a.info("TRANSCRIPT","Watching transcript file",{file:e,watch:t.name,schema:n.name})}async handleLine(e,t,n,o,i){try{let s=JSON.parse(e);await this.processor.processEntry(s,t,n,i??void 0)}catch(s){s instanceof Error?a.debug("TRANSCRIPT","Failed to parse transcript line",{watch:t.name,file:(0,O.basename)(o)},s):a.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:t.name,file:(0,O.basename)(o),error:String(s)})}}extractSessionIdFromPath(e){let t=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return t?t[0]:null}};function vt(r,e){let t=r.indexOf(e);return t===-1?null:r[t+1]??null}async function Zr(r,e){switch(r){case"init":{let t=vt(e,"--config")??ne;return Ce(t),console.log(`Created sample config: ${b(t)}`),0}case"watch":{let t=vt(e,"--config")??ne,n;try{n=pe(t)}catch(c){if(c instanceof Error&&c.message.includes("not found"))Ce(t),console.log(`Created sample config: ${b(t)}`),n=pe(t);else throw c}let o=b(n.stateFile??Me),i=new Qe(n,o);await i.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let s=()=>{i.stop(),process.exit(0)};return process.on("SIGINT",s),process.on("SIGTERM",s),await new Promise(()=>{})}case"validate":{let t=vt(e,"--config")??ne;try{pe(t)}catch(n){if(n instanceof Error&&n.message.includes("not found"))Ce(t),console.log(`Created sample config: ${b(t)}`),pe(t);else throw n}return console.log(`Config OK: ${b(t)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var $o=process.argv[2],Go=process.argv.slice(3);Zr($o,Go).then(r=>{process.exit(r)}).catch(r=>{console.error(r),process.exit(1)});