Files
claude-mem/plugin/scripts/summary-hook.js

14 lines
13 KiB
JavaScript
Executable File

#!/usr/bin/env bun
import{stdin as B}from"process";function V(s,t,e){return s==="SessionStart"?t&&e.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{continue:!0,suppressOutput:!0}:s==="UserPromptSubmit"||s==="PostToolUse"?{continue:!0,suppressOutput:!0}:s==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...e.reason&&!t?{stopReason:e.reason}:{}}}function w(s,t,e={}){let r=V(s,t,e);return JSON.stringify(r)}import{readFileSync as J,writeFileSync as q,existsSync as z}from"fs";import{join as Q}from"path";import{homedir as Z}from"os";var X=["bugfix","feature","refactor","discovery","decision","change"],Y=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var P=X.join(","),b=Y.join(",");var l=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:Q(Z(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:P,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:b,CLAUDE_MEM_CONTEXT_FULL_COUNT:"5",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"};static getAllDefaults(){return{...this.DEFAULTS}}static get(t){return this.DEFAULTS[t]}static getInt(t){let e=this.get(t);return parseInt(e,10)}static getBool(t){return this.get(t)==="true"}static loadFromFile(t){if(!z(t))return this.getAllDefaults();let e=J(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{q(t,JSON.stringify(n,null,2),"utf-8"),c.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){c.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(o[i]=n[i]);return o}};var h=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(h||{}),A=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=l.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=h[t]??1}return this.level}correlationId(t,e){return`obs-${t}-${e}`}sessionId(t){return`session-${t}`}formatData(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return t.toString();if(typeof t=="object"){if(t instanceof Error)return this.getLevel()===0?`${t.message}
${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let e=Object.keys(t);return e.length===0?"{}":e.length<=3?JSON.stringify(t):`{${e.length} keys: ${e.slice(0,3).join(", ")}...}`}return String(t)}formatTool(t,e){if(!e)return t;try{let r=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&r.command){let n=r.command.length>50?r.command.substring(0,50)+"...":r.command;return`${t}(${n})`}if(t==="Read"&&r.file_path){let n=r.file_path.split("/").pop()||r.file_path;return`${t}(${n})`}if(t==="Edit"&&r.file_path){let n=r.file_path.split("/").pop()||r.file_path;return`${t}(${n})`}if(t==="Write"&&r.file_path){let n=r.file_path.split("/").pop()||r.file_path;return`${t}(${n})`}return t}catch{return t}}log(t,e,r,n,o){if(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),a=h[t].padEnd(5),p=e.padEnd(6),u="";n?.correlationId?u=`[${n.correlationId}] `:n?.sessionId&&(u=`[session-${n.sessionId}] `);let m="";o!=null&&(this.getLevel()===0&&typeof o=="object"?m=`
`+JSON.stringify(o,null,2):m=" "+this.formatData(o));let R="";if(n){let{sessionId:It,sdkSessionId:Ut,correlationId:wt,...U}=n;Object.keys(U).length>0&&(R=` {${Object.entries(U).map(([j,G])=>`${j}=${G}`).join(", ")}}`)}let I=`[${i}] [${a}] [${p}] ${u}${r}${R}${m}`;t===3?console.error(I):console.log(I)}debug(t,e,r,n){this.log(0,t,e,r,n)}info(t,e,r,n){this.log(1,t,e,r,n)}warn(t,e,r,n){this.log(2,t,e,r,n)}error(t,e,r,n){this.log(3,t,e,r,n)}dataIn(t,e,r,n){this.info(t,`\u2192 ${e}`,r,n)}dataOut(t,e,r,n){this.info(t,`\u2190 ${e}`,r,n)}success(t,e,r,n){this.info(t,`\u2713 ${e}`,r,n)}failure(t,e,r,n){this.error(t,`\u2717 ${e}`,r,n)}timing(t,e,r,n){this.info(t,`\u23F1 ${e}`,n,{duration:`${r}ms`})}},c=new A;import L from"path";import{homedir as gt}from"os";import{spawnSync as St}from"child_process";import{existsSync as dt,writeFileSync as H}from"fs";var g={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function N(s){return process.platform==="win32"?Math.round(s*g.WINDOWS_MULTIPLIER):s}import{existsSync as M,readFileSync as st,writeFileSync as ot,unlinkSync as it,mkdirSync as k}from"fs";import{createWriteStream as at}from"fs";import{join as d}from"path";import{spawn as ct,spawnSync as ut}from"child_process";import{homedir as pt}from"os";import{join as f,dirname as tt,basename as Gt}from"path";import{homedir as et}from"os";import{fileURLToPath as rt}from"url";function nt(){return typeof __dirname<"u"?__dirname:tt(rt(import.meta.url))}var qt=nt(),E=l.get("CLAUDE_MEM_DATA_DIR"),C=process.env.CLAUDE_CONFIG_DIR||f(et(),".claude"),zt=f(E,"archives"),Qt=f(E,"logs"),Zt=f(E,"trash"),te=f(E,"backups"),ee=f(E,"settings.json"),re=f(E,"claude-mem.db"),ne=f(E,"vector-db"),se=f(C,"settings.json"),oe=f(C,"commands"),ie=f(C,"CLAUDE.md");var S=d(E,"worker.pid"),v=d(E,"logs"),x=d(pt(),".claude","plugins","marketplaces","thedotmack"),lt=5e3,ft=1e4,Et=200,mt=1e3,_t=100,T=class{static async start(t){if(isNaN(t)||t<1024||t>65535)return{success:!1,error:`Invalid port ${t}. Must be between 1024 and 65535`};if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};k(v,{recursive:!0});let e=d(x,"plugin","scripts","worker-service.cjs");if(!M(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){try{return ut("bun",["--version"],{stdio:"pipe",timeout:5e3}).status===0}catch{return!1}}static async startWithBun(t,e,r){if(!this.isBunAvailable())return{success:!1,error:"Bun is required but not found in PATH. Install from https://bun.sh"};try{let n=process.platform==="win32",o=ct("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:x,...n&&{windowsHide:!0}}),i=at(e,{flags:"a"});return o.stdout?.pipe(i),o.stderr?.pipe(i),o.unref(),o.pid?(this.writePidFile({pid:o.pid,port:r,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(o.pid,r)):{success:!1,error:"Failed to get PID from spawned process"}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}static async stop(t=lt){let e=this.getPidInfo();if(!e)return!0;try{process.kill(e.pid,"SIGTERM"),await this.waitForExit(e.pid,t)}catch{try{process.kill(e.pid,"SIGKILL")}catch{}}return this.removePidFile(),!0}static async restart(t){return await this.stop(),this.start(t)}static async status(){let t=this.getPidInfo();if(!t)return{running:!1};let e=this.isProcessAlive(t.pid);return{running:e,pid:e?t.pid:void 0,port:e?t.port:void 0,uptime:e?this.formatUptime(t.startedAt):void 0}}static async isRunning(){let t=this.getPidInfo();if(!t)return!1;let e=this.isProcessAlive(t.pid);return e||this.removePidFile(),e}static getPidInfo(){try{if(!M(S))return null;let t=st(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){k(E,{recursive:!0}),ot(S,JSON.stringify(t,null,2))}static removePidFile(){try{M(S)&&it(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=ft){let n=Date.now();for(;Date.now()-n<r;){if(!this.isProcessAlive(t))return{success:!1,error:"Process died during startup"};try{if((await fetch(`http://127.0.0.1:${e}/health`,{signal:AbortSignal.timeout(mt)})).ok)return{success:!0,pid:t}}catch{}await new Promise(o=>setTimeout(o,Et))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-r<e;){if(!this.isProcessAlive(t))return;await new Promise(n=>setTimeout(n,_t))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return d(v,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),n=Date.now()-e,o=Math.floor(n/1e3),i=Math.floor(o/60),a=Math.floor(i/60),p=Math.floor(a/24);return p>0?`${p}d ${a%24}h`:a>0?`${a}h ${i%60}m`:i>0?`${i}m ${o%60}s`:`${o}s`}};var Ot=L.join(gt(),".claude","plugins","marketplaces","thedotmack"),Tt=N(g.HEALTH_CHECK),_=null;function O(){if(_!==null)return _;try{let s=L.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(s);return _=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),_}catch(s){return c.debug("SYSTEM","Failed to load port from settings, using default",{error:s}),_=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),_}}async function $(){try{let s=O();return(await fetch(`http://127.0.0.1:${s}/health`,{signal:AbortSignal.timeout(Tt)})).ok}catch(s){return c.debug("SYSTEM","Worker health check failed",{error:s instanceof Error?s.message:String(s),errorType:s?.constructor?.name}),!1}}async function ht(){let s=L.join(l.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(!dt(s))try{St("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),H(s,new Date().toISOString(),"utf-8"),c.debug("SYSTEM","PM2 cleanup completed and marked")}catch{H(s,new Date().toISOString(),"utf-8")}let t=O(),e=await T.start(t);return e.success||c.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:Ot}),e.success}async function F(){if(await $())return;let s=await ht();if(!(!s&&await $())&&!s){let t=O();throw new Error(`Worker service failed to start on port ${t}.
To start manually, run: npm run worker:start
If already running, try: npm run worker:restart`)}}import{appendFileSync as At}from"fs";import{homedir as Ct}from"os";import{join as Mt}from"path";var Lt=Mt(Ct(),".claude-mem","silent.log");function W(s,t,e=""){let r=new Date().toISOString(),a=((new Error().stack||"").split(`
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),p=a?`${a[1].split("/").pop()}:${a[2]}`:"unknown",u=`[${r}] [HAPPY-PATH-ERROR] [${p}] ${s}`;if(t!==void 0)try{u+=` ${JSON.stringify(t)}`}catch(m){u+=` [stringify error: ${m}]`}u+=`
`;try{At(Lt,u)}catch(m){console.error("[silent-debug] Failed to write to log:",m)}return e}function K(s){throw s.cause?.code==="ECONNREFUSED"||s.name==="TimeoutError"||s.message?.includes("fetch failed")?new Error("There's a problem with the worker. Try: npm run worker:restart"):s}import{readFileSync as Dt,existsSync as yt}from"fs";function D(s,t,e=!1){if(!s||!yt(s))return"";try{let r=Dt(s,"utf-8").trim();if(!r)return"";let n=r.split(`
`);for(let o=n.length-1;o>=0;o--)try{let i=JSON.parse(n[o]);if(i.type===t&&i.message?.content){let a="",p=i.message.content;return typeof p=="string"?a=p:Array.isArray(p)&&(a=p.filter(u=>u.type==="text").map(u=>u.text).join(`
`)),e&&(a=a.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,""),a=a.replace(/\n{3,}/g,`
`).trim()),a}}catch{continue}}catch(r){c.error("HOOK","Failed to read transcript",{transcriptPath:s},r)}return""}async function Rt(s){if(await F(),!s)throw new Error("summaryHook requires input");let{session_id:t}=s,e=O(),r=W("Missing transcript_path in Stop hook input",{session_id:t},s.transcript_path||""),n=D(r,"user"),o=D(r,"assistant",!0);c.dataIn("HOOK","Stop: Requesting summary",{workerPort:e,hasLastUserMessage:!!n,hasLastAssistantMessage:!!o});try{let i=await fetch(`http://127.0.0.1:${e}/api/sessions/summarize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,last_user_message:n,last_assistant_message:o}),signal:AbortSignal.timeout(g.DEFAULT)});if(!i.ok){let a=await i.text();throw c.failure("HOOK","Failed to generate summary",{status:i.status},a),new Error(`Failed to request summary from worker: ${i.status} ${a}`)}c.debug("HOOK","Summary request sent successfully")}catch(i){K(i)}finally{try{let i=await fetch(`http://127.0.0.1:${e}/api/processing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({isProcessing:!1}),signal:AbortSignal.timeout(2e3)});i.ok||c.warn("HOOK","Failed to stop spinner",{status:i.status})}catch(i){c.warn("HOOK","Could not stop spinner",{error:i.message})}}console.log(w("Stop",!0))}var y="";B.on("data",s=>y+=s);B.on("end",async()=>{let s=y?JSON.parse(y):void 0;await Rt(s)});