Enhance error handling and logging in early-settings and worker-utils
- Added silent debugging for settings file loading failures in early-settings.ts. - Improved error logging in worker-utils.ts for health check and worker startup failures, including detailed error information and context.
This commit is contained in:
@@ -1,16 +1,18 @@
|
||||
#!/usr/bin/env node
|
||||
import{stdin as x}from"process";import{readFileSync as P,existsSync as w}from"fs";function H(o,t,e){return o==="PreCompact"?t?{continue:!0,suppressOutput:!0}:{continue:!1,stopReason:e.reason||"Pre-compact operation failed",suppressOutput:!0}:o==="SessionStart"?t&&e.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{continue:!0,suppressOutput:!0}:o==="UserPromptSubmit"||o==="PostToolUse"?{continue:!0,suppressOutput:!0}:o==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...e.reason&&!t?{stopReason:e.reason}:{}}}function A(o,t,e={}){let r=H(o,t,e);return JSON.stringify(r)}import{join as v}from"path";import{homedir as $}from"os";import{existsSync as W,readFileSync as F}from"fs";var M=v($(),".claude-mem","settings.json");function L(o,t){try{if(W(M)){let r=JSON.parse(F(M,"utf-8")).env?.[o];if(r!==void 0)return r}}catch{}return process.env[o]||t}var O=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(O||{}),S=class{level;useColor;constructor(){let t=L("CLAUDE_MEM_LOG_LEVEL","INFO").toUpperCase();this.level=O[t]??1,this.useColor=process.stdout.isTTY??!1}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.level===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,s){if(t<this.level)return;let i=new Date().toISOString().replace("T"," ").substring(0,23),c=O[t].padEnd(5),E=e.padEnd(6),l="";n?.correlationId?l=`[${n.correlationId}] `:n?.sessionId&&(l=`[session-${n.sessionId}] `);let g="";s!=null&&(this.level===0&&typeof s=="object"?g=`
|
||||
`+JSON.stringify(s,null,2):g=" "+this.formatData(s));let C="";if(n){let{sessionId:et,sdkSessionId:rt,correlationId:nt,...y}=n;Object.keys(y).length>0&&(C=` {${Object.entries(y).map(([k,b])=>`${k}=${b}`).join(", ")}}`)}let d=`[${i}] [${c}] [${E}] ${l}${r}${C}${g}`;t===3?console.error(d):console.log(d)}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`})}},u=new S;import p from"path";import{existsSync as m}from"fs";import{homedir as R}from"os";import{spawnSync as D}from"child_process";import{readFileSync as X,existsSync as B}from"fs";import{join as K}from"path";import{homedir as G}from"os";var j=["bugfix","feature","refactor","discovery","decision","change"],V=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var h=j.join(","),N=V.join(",");var _=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_DATA_DIR:K(G(),".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:h,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:N,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 process.env[t]||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(!B(t))return this.getAllDefaults();let e=X(t,"utf-8"),n=JSON.parse(e).env||{},s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(s[i]=n[i]);return s}};var a=p.join(R(),".claude","plugins","marketplaces","thedotmack"),Y=500,J=1e3,q=15;function f(){let o=p.join(R(),".claude-mem","settings.json"),t=_.loadFromFile(o);return parseInt(t.CLAUDE_MEM_WORKER_PORT,10)}async function U(){try{let o=f();return(await fetch(`http://127.0.0.1:${o}/health`,{signal:AbortSignal.timeout(Y)})).ok}catch{return!1}}async function z(){try{let o=p.join(a,"plugin","scripts","worker-service.cjs");if(!m(o))throw new Error(`Worker script not found at ${o}`);if(process.platform==="win32"){let t=D("powershell.exe",["-NoProfile","-NonInteractive","-Command",`Start-Process -FilePath 'node' -ArgumentList '${o}' -WorkingDirectory '${a}' -WindowStyle Hidden`],{cwd:a,stdio:"pipe",encoding:"utf-8",windowsHide:!0});if(t.status!==0)throw new Error(t.stderr||"PowerShell Start-Process failed")}else{let t=p.join(a,"ecosystem.config.cjs");if(!m(t))throw new Error(`Ecosystem config not found at ${t}`);let e=p.join(a,"node_modules",".bin","pm2"),r=m(e)?e:"pm2",n=D(r,["start",t],{cwd:a,stdio:"pipe",encoding:"utf-8"});if(n.status!==0)throw new Error(n.stderr||"PM2 start failed")}for(let t=0;t<q;t++)if(await new Promise(e=>setTimeout(e,J)),await U())return!0;return!1}catch{return!1}}async function I(){if(await U())return;if(!await z()){let t=f();throw new Error(`Worker service failed to start on port ${t}.
|
||||
import{stdin as w}from"process";import{readFileSync as x,existsSync as P}from"fs";function v(n,t,e){return n==="PreCompact"?t?{continue:!0,suppressOutput:!0}:{continue:!1,stopReason:e.reason||"Pre-compact operation failed",suppressOutput:!0}:n==="SessionStart"?t&&e.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{continue:!0,suppressOutput:!0}:n==="UserPromptSubmit"||n==="PostToolUse"?{continue:!0,suppressOutput:!0}:n==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...e.reason&&!t?{stopReason:e.reason}:{}}}function L(n,t,e={}){let r=v(n,t,e);return JSON.stringify(r)}import{join as V}from"path";import{homedir as X}from"os";import{existsSync as B,readFileSync as K}from"fs";import{appendFileSync as H}from"fs";import{homedir as F}from"os";import{join as W}from"path";var j=W(F(),".claude-mem","silent.log");function M(n,t,e=""){let r=new Date().toISOString(),a=((new Error().stack||"").split(`
|
||||
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),E=a?`${a[1].split("/").pop()}:${a[2]}`:"unknown",u=`[${r}] [${E}] ${n}`;if(t!==void 0)try{u+=` ${JSON.stringify(t)}`}catch(l){u+=` [stringify error: ${l}]`}u+=`
|
||||
`;try{H(j,u)}catch(l){console.error("[silent-debug] Failed to write to log:",l)}return e}var S=V(X(),".claude-mem","settings.json");function h(n,t){try{if(B(S)){let r=JSON.parse(K(S,"utf-8")).env?.[n];if(r!==void 0)return r}}catch(e){M("Failed to load settings file",{error:e,settingsPath:S,key:n})}return process.env[n]||t}var m=(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))(m||{}),O=class{level;useColor;constructor(){let t=h("CLAUDE_MEM_LOG_LEVEL","INFO").toUpperCase();this.level=m[t]??1,this.useColor=process.stdout.isTTY??!1}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.level===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 s=r.command.length>50?r.command.substring(0,50)+"...":r.command;return`${t}(${s})`}if(t==="Read"&&r.file_path){let s=r.file_path.split("/").pop()||r.file_path;return`${t}(${s})`}if(t==="Edit"&&r.file_path){let s=r.file_path.split("/").pop()||r.file_path;return`${t}(${s})`}if(t==="Write"&&r.file_path){let s=r.file_path.split("/").pop()||r.file_path;return`${t}(${s})`}return t}catch{return t}}log(t,e,r,s,o){if(t<this.level)return;let i=new Date().toISOString().replace("T"," ").substring(0,23),a=m[t].padEnd(5),E=e.padEnd(6),u="";s?.correlationId?u=`[${s.correlationId}] `:s?.sessionId&&(u=`[session-${s.sessionId}] `);let l="";o!=null&&(this.level===0&&typeof o=="object"?l=`
|
||||
`+JSON.stringify(o,null,2):l=" "+this.formatData(o));let y="";if(s){let{sessionId:it,sdkSessionId:at,correlationId:ct,...A}=s;Object.keys(A).length>0&&(y=` {${Object.entries(A).map(([$,b])=>`${$}=${b}`).join(", ")}}`)}let C=`[${i}] [${a}] [${E}] ${u}${r}${y}${l}`;t===3?console.error(C):console.log(C)}debug(t,e,r,s){this.log(0,t,e,r,s)}info(t,e,r,s){this.log(1,t,e,r,s)}warn(t,e,r,s){this.log(2,t,e,r,s)}error(t,e,r,s){this.log(3,t,e,r,s)}dataIn(t,e,r,s){this.info(t,`\u2192 ${e}`,r,s)}dataOut(t,e,r,s){this.info(t,`\u2190 ${e}`,r,s)}success(t,e,r,s){this.info(t,`\u2713 ${e}`,r,s)}failure(t,e,r,s){this.error(t,`\u2717 ${e}`,r,s)}timing(t,e,r,s){this.info(t,`\u23F1 ${e}`,s,{duration:`${r}ms`})}},c=new O;import f from"path";import{existsSync as T}from"fs";import{homedir as U}from"os";import{spawnSync as R}from"child_process";import{readFileSync as J,existsSync as q}from"fs";import{join as z}from"path";import{homedir as Q}from"os";var G=["bugfix","feature","refactor","discovery","decision","change"],Y=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var D=G.join(","),N=Y.join(",");var g=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_DATA_DIR:z(Q(),".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:D,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:N,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 process.env[t]||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(!q(t))return this.getAllDefaults();let e=J(t,"utf-8"),s=JSON.parse(e).env||{},o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))s[i]!==void 0&&(o[i]=s[i]);return o}};var p=f.join(U(),".claude","plugins","marketplaces","thedotmack"),Z=500,tt=1e3,et=15;function _(){let n=f.join(U(),".claude-mem","settings.json"),t=g.loadFromFile(n);return parseInt(t.CLAUDE_MEM_WORKER_PORT,10)}async function I(){try{let n=_();return(await fetch(`http://127.0.0.1:${n}/health`,{signal:AbortSignal.timeout(Z)})).ok}catch(n){return c.debug("SYSTEM","Worker health check failed",{error:n instanceof Error?n.message:String(n),errorType:n?.constructor?.name}),!1}}async function rt(){try{let n=f.join(p,"plugin","scripts","worker-service.cjs");if(!T(n))throw new Error(`Worker script not found at ${n}`);if(process.platform==="win32"){let t=R("powershell.exe",["-NoProfile","-NonInteractive","-Command",`Start-Process -FilePath 'node' -ArgumentList '${n}' -WorkingDirectory '${p}' -WindowStyle Hidden`],{cwd:p,stdio:"pipe",encoding:"utf-8",windowsHide:!0});if(t.status!==0)throw new Error(t.stderr||"PowerShell Start-Process failed")}else{let t=f.join(p,"ecosystem.config.cjs");if(!T(t))throw new Error(`Ecosystem config not found at ${t}`);let e=f.join(p,"node_modules",".bin","pm2"),r=T(e)?e:"pm2",s=R(r,["start",t],{cwd:p,stdio:"pipe",encoding:"utf-8"});if(s.status!==0)throw new Error(s.stderr||"PM2 start failed")}for(let t=0;t<et;t++)if(await new Promise(e=>setTimeout(e,tt)),await I())return!0;return!1}catch(n){return c.error("SYSTEM","Failed to start worker",{platform:process.platform,workerScript:f.join(p,"plugin","scripts","worker-service.cjs"),error:n instanceof Error?n.message:String(n),marketplaceRoot:p}),!1}}async function k(){if(await I())return;if(!await rt()){let t=_();throw new Error(`Worker service failed to start on port ${t}.
|
||||
|
||||
To start manually, run:
|
||||
cd ${a}
|
||||
cd ${p}
|
||||
npx pm2 start ecosystem.config.cjs
|
||||
|
||||
If already running, try: npx pm2 restart claude-mem-worker`)}}function Q(o){if(!o||!w(o))return"";try{let t=P(o,"utf-8").trim();if(!t)return"";let e=t.split(`
|
||||
`);for(let r=e.length-1;r>=0;r--)try{let n=JSON.parse(e[r]);if(n.type==="user"&&n.message?.content){let s=n.message.content;if(typeof s=="string")return s;if(Array.isArray(s))return s.filter(c=>c.type==="text").map(c=>c.text).join(`
|
||||
`)}}catch{continue}}catch(t){u.error("HOOK","Failed to read transcript",{transcriptPath:o},t)}return""}function Z(o){if(!o||!w(o))return"";try{let t=P(o,"utf-8").trim();if(!t)return"";let e=t.split(`
|
||||
`);for(let r=e.length-1;r>=0;r--)try{let n=JSON.parse(e[r]);if(n.type==="assistant"&&n.message?.content){let s="",i=n.message.content;return typeof i=="string"?s=i:Array.isArray(i)&&(s=i.filter(E=>E.type==="text").map(E=>E.text).join(`
|
||||
`)),s=s.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,""),s=s.replace(/\n{3,}/g,`
|
||||
If already running, try: npx pm2 restart claude-mem-worker`)}}function nt(n){if(!n||!P(n))return"";try{let t=x(n,"utf-8").trim();if(!t)return"";let e=t.split(`
|
||||
`);for(let r=e.length-1;r>=0;r--)try{let s=JSON.parse(e[r]);if(s.type==="user"&&s.message?.content){let o=s.message.content;if(typeof o=="string")return o;if(Array.isArray(o))return o.filter(a=>a.type==="text").map(a=>a.text).join(`
|
||||
`)}}catch{continue}}catch(t){c.error("HOOK","Failed to read transcript",{transcriptPath:n},t)}return""}function st(n){if(!n||!P(n))return"";try{let t=x(n,"utf-8").trim();if(!t)return"";let e=t.split(`
|
||||
`);for(let r=e.length-1;r>=0;r--)try{let s=JSON.parse(e[r]);if(s.type==="assistant"&&s.message?.content){let o="",i=s.message.content;return typeof i=="string"?o=i:Array.isArray(i)&&(o=i.filter(E=>E.type==="text").map(E=>E.text).join(`
|
||||
`)),o=o.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,""),o=o.replace(/\n{3,}/g,`
|
||||
|
||||
`).trim(),s}}catch{continue}}catch(t){u.error("HOOK","Failed to read transcript",{transcriptPath:o},t)}return""}async function tt(o){if(await I(),!o)throw new Error("summaryHook requires input");let{session_id:t}=o,e=f(),r=Q(o.transcript_path||""),n=Z(o.transcript_path||"");u.dataIn("HOOK","Stop: Requesting summary",{workerPort:e,hasLastUserMessage:!!r,hasLastAssistantMessage:!!n});try{let s=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:r,last_assistant_message:n}),signal:AbortSignal.timeout(2e3)});if(!s.ok){let i=await s.text();throw u.failure("HOOK","Failed to generate summary",{status:s.status},i),new Error(`Failed to request summary from worker: ${s.status} ${i}`)}u.debug("HOOK","Summary request sent successfully")}catch(s){throw s.cause?.code==="ECONNREFUSED"||s.name==="TimeoutError"||s.message.includes("fetch failed")?new Error("There's a problem with the worker. If you just updated, type `pm2 restart claude-mem-worker` in your terminal to continue"):s}finally{fetch(`http://127.0.0.1:${e}/api/processing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({isProcessing:!1})}).catch(()=>{})}console.log(A("Stop",!0))}var T="";x.on("data",o=>T+=o);x.on("end",async()=>{let o=T?JSON.parse(T):void 0;await tt(o)});
|
||||
`).trim(),o}}catch{continue}}catch(t){c.error("HOOK","Failed to read transcript",{transcriptPath:n},t)}return""}async function ot(n){if(await k(),!n)throw new Error("summaryHook requires input");let{session_id:t}=n,e=_(),r=nt(n.transcript_path||""),s=st(n.transcript_path||"");c.dataIn("HOOK","Stop: Requesting summary",{workerPort:e,hasLastUserMessage:!!r,hasLastAssistantMessage:!!s});try{let o=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:r,last_assistant_message:s}),signal:AbortSignal.timeout(2e3)});if(!o.ok){let i=await o.text();throw c.failure("HOOK","Failed to generate summary",{status:o.status},i),new Error(`Failed to request summary from worker: ${o.status} ${i}`)}c.debug("HOOK","Summary request sent successfully")}catch(o){throw o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError"||o.message.includes("fetch failed")?new Error("There's a problem with the worker. If you just updated, type `pm2 restart claude-mem-worker` in your terminal to continue"):o}finally{fetch(`http://127.0.0.1:${e}/api/processing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({isProcessing:!1})}).catch(()=>{})}console.log(L("Stop",!0))}var d="";w.on("data",n=>d+=n);w.on("end",async()=>{let n=d?JSON.parse(d):void 0;await ot(n)});
|
||||
|
||||
Reference in New Issue
Block a user