claude-mem 13.12.1 → 13.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +284 -284
- package/dist/opencode-plugin/index.js +1 -1
- package/openclaw/install.sh +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/openclaw/test-install.sh +1 -1
- package/openclaw/tsconfig.json +2 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.mcp.json +1 -1
- package/plugin/hooks/hooks.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/bun-runner.js +33 -4
- package/plugin/scripts/context-generator.cjs +28 -888
- package/plugin/scripts/mcp-server.cjs +29 -29
- package/plugin/scripts/server-service.cjs +127 -127
- package/plugin/scripts/transcript-watcher.cjs +17 -17
- package/plugin/scripts/worker-service.cjs +1755 -1711
- package/plugin/scripts/worker-wrapper.cjs +1 -1
- package/plugin/skills/version-bump/SKILL.md +1 -1
- package/plugin/sqlite/SessionStore.js +41 -41
- package/plugin/sqlite/observations/files.js +7 -7
- package/plugin/ui/viewer-bundle.js +12 -12
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
"use strict";var m=Object.create;var w=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var f=Object.getPrototypeOf,x=Object.prototype.hasOwnProperty;var g=(e,i,n,o)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of I(i))!x.call(e,s)&&s!==n&&w(e,s,{get:()=>i[s],enumerable:!(o=u(i,s))||o.enumerable});return e};var k=(e,i,n)=>(n=e!=null?m(f(e)):{},g(i||!e||!e.__esModule?w(n,"default",{value:e,enumerable:!0}):n,e));var c=require("child_process"),p=k(require("path"),1),y=process.platform==="win32",P=__dirname,l=p.default.join(P,"worker-service.cjs"),t=null,a=!1;function r(e){let i=new Date().toISOString();console.log(`[${i}] [wrapper] ${e}`)}function h(){r(`Spawning inner worker: ${l}`),t=(0,c.spawn)(process.execPath,[l],{stdio:["inherit","inherit","inherit","ipc"],env:{...process.env,CLAUDE_MEM_MANAGED:"true"},cwd:p.default.dirname(l)}),t.on("message",async e=>{(e.type==="restart"||e.type==="shutdown")&&(r(`${e.type} requested by inner`),a=!0,await d(),r("Exiting wrapper"),process.exit(0))}),t.on("exit",(e,i)=>{r(`Inner exited with code=${e}, signal=${i}`),t=null,a||(r("Inner exited unexpectedly, wrapper exiting (hooks will restart if needed)"),process.exit(e??0))}),t.on("error",e=>{r(`Inner error: ${e.message}`)})}async function d(){if(!t||!t.pid){r("No inner process to kill");return}let e=t.pid;if(r(`Killing inner process tree (pid=${e})`),y)try{(0,c.execSync)(`taskkill /PID ${e} /T /F`,{timeout:1e4,stdio:"ignore"}),r(`taskkill completed for pid=${e}`)}catch(i){r(`taskkill failed (process may be dead): ${i}`)}else{t.kill("SIGTERM");let i=new Promise(o=>{if(!t){o();return}t.on("exit",()=>o())}),n=new Promise(o=>setTimeout(()=>o(),5e3));await Promise.race([i,n]),t&&!t.killed&&(r("Inner did not exit gracefully, force killing"),t.kill("SIGKILL"))}await S(e,5e3),t=null,r("Inner process terminated")}async function S(e,i){let n=Date.now();for(;Date.now()-n<i;)try{process.kill(e,0),await new Promise(o=>setTimeout(o,100))}catch{return}r(`Timeout waiting for process ${e} to exit`)}process.on("SIGTERM",async()=>{r("Wrapper received SIGTERM"),a=!0,await d(),process.exit(0)});process.on("SIGINT",async()=>{r("Wrapper received SIGINT"),a=!0,await d(),process.exit(0)});r("Wrapper starting");h();
|
|
2
|
+
"use strict";var m=Object.create;var w=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var f=Object.getPrototypeOf,x=Object.prototype.hasOwnProperty;var g=(e,i,n,o)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of I(i))!x.call(e,s)&&s!==n&&w(e,s,{get:()=>i[s],enumerable:!(o=u(i,s))||o.enumerable});return e};var k=(e,i,n)=>(n=e!=null?m(f(e)):{},g(i||!e||!e.__esModule?w(n,"default",{value:e,enumerable:!0}):n,e));var c=require("child_process"),p=k(require("path"),1),y=process.platform==="win32",P=__dirname,l=p.default.join(P,"worker-service.cjs"),t=null,a=!1;function r(e){let i=new Date().toISOString();console.log(`[${i}] [wrapper] ${e}`)}function h(){r(`Spawning inner worker: ${l}`),t=(0,c.spawn)(process.execPath,[l],{stdio:["inherit","inherit","inherit","ipc"],env:{...process.env,CLAUDE_MEM_MANAGED:"true"},cwd:p.default.dirname(l),windowsHide:!0}),t.on("message",async e=>{(e.type==="restart"||e.type==="shutdown")&&(r(`${e.type} requested by inner`),a=!0,await d(),r("Exiting wrapper"),process.exit(0))}),t.on("exit",(e,i)=>{r(`Inner exited with code=${e}, signal=${i}`),t=null,a||(r("Inner exited unexpectedly, wrapper exiting (hooks will restart if needed)"),process.exit(e??0))}),t.on("error",e=>{r(`Inner error: ${e.message}`)})}async function d(){if(!t||!t.pid){r("No inner process to kill");return}let e=t.pid;if(r(`Killing inner process tree (pid=${e})`),y)try{(0,c.execSync)(`taskkill /PID ${e} /T /F`,{timeout:1e4,stdio:"ignore",windowsHide:!0}),r(`taskkill completed for pid=${e}`)}catch(i){r(`taskkill failed (process may be dead): ${i}`)}else{t.kill("SIGTERM");let i=new Promise(o=>{if(!t){o();return}t.on("exit",()=>o())}),n=new Promise(o=>setTimeout(()=>o(),5e3));await Promise.race([i,n]),t&&!t.killed&&(r("Inner did not exit gracefully, force killing"),t.kill("SIGKILL"))}await S(e,5e3),t=null,r("Inner process terminated")}async function S(e,i){let n=Date.now();for(;Date.now()-n<i;)try{process.kill(e,0),await new Promise(o=>setTimeout(o,100))}catch{return}r(`Timeout waiting for process ${e} to exit`)}process.on("SIGTERM",async()=>{r("Wrapper received SIGTERM"),a=!0,await d(),process.exit(0)});process.on("SIGINT",async()=>{r("Wrapper received SIGINT"),a=!0,await d(),process.exit(0)});r("Wrapper starting");h();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
---
|
|
2
|
-
name:
|
|
2
|
+
name: version-bump
|
|
3
3
|
description: Automated semantic versioning and release workflow for Claude Code plugins. Handles version increments across package.json, marketplace.json, plugin.json manifests, build verification, git tagging, GitHub releases, and changelog generation. NPM publishing (so `npx claude-mem@X.Y.Z` resolves) is handed off to the human maintainer, who raised npm security.
|
|
4
4
|
---
|
|
5
5
|
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
var __IMPORT_META_URL__ = require("node:url").pathToFileURL(__filename).href;
|
|
2
|
-
"use strict";var
|
|
3
|
-
${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 s=t;if(typeof t=="string")try{s=JSON.parse(t)}catch{s=t}if(e==="Bash"&&s.command)return`${e}(${s.command})`;if(s.file_path)return`${e}(${s.file_path})`;if(s.notebook_path)return`${e}(${s.notebook_path})`;if(e==="Glob"&&s.pattern)return`${e}(${s.pattern})`;if(e==="Grep"&&s.pattern)return`${e}(${s.pattern})`;if(s.url)return`${e}(${s.url})`;if(s.query)return`${e}(${s.query})`;if(e==="Task"){if(s.subagent_type)return`${e}(${s.subagent_type})`;if(s.description)return`${e}(${s.description})`}return e==="Skill"&&s.skill?`${e}(${s.skill})`:e==="LSP"&&s.operation?`${e}(${s.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),r=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),_=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${s}-${n} ${r}:${o}:${a}.${_}`}log(e,t,s,n,r){if(e<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=
|
|
2
|
+
"use strict";var $=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var ge=(i,e)=>{for(var t in e)$(i,t,{get:e[t],enumerable:!0})},Se=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of be(e))!fe.call(i,n)&&n!==t&&$(i,n,{get:()=>e[n],enumerable:!(s=Te(e,n))||s.enumerable});return i};var Ne=i=>Se($({},"__esModule",{value:!0}),i);var Ge={};ge(Ge,{SessionStore:()=>Q});module.exports=Ne(Ge);var J=require("bun:sqlite"),Ee=require("crypto");var b=require("path"),M=require("os"),U=require("fs"),Z=require("url");var he=null;function Re(i){return(he??process.stderr.write.bind(process.stderr))(i)}function k(i){Re(i)}var We=process.platform==="win32";function Ie(i){return i.replace(/^\uFEFF/,"")}function X(i){return JSON.parse(Ie(i))}function Oe(){return typeof __dirname<"u"?__dirname:(0,b.dirname)((0,Z.fileURLToPath)(__IMPORT_META_URL__))}var Ke=Oe();function z(i){return typeof i!="string"||i.length===0?i:i==="~"?(0,M.homedir)():i.startsWith("~/")?(0,b.join)((0,M.homedir)(),i.slice(2)):i}function Ae(){if(process.env.CLAUDE_MEM_DATA_DIR)return z(process.env.CLAUDE_MEM_DATA_DIR);let i=(0,b.join)((0,M.homedir)(),".claude-mem"),e=(0,b.join)(i,"settings.json");try{if((0,U.existsSync)(e)){let t=X((0,U.readFileSync)(e,"utf-8")),s=t.env??t;if(s.CLAUDE_MEM_DATA_DIR)return z(s.CLAUDE_MEM_DATA_DIR)}}catch{}return i}var I=Ae(),Le=process.env.CLAUDE_CONFIG_DIR||(0,b.join)((0,M.homedir)(),".claude"),Je=(0,b.join)(Le,"plugins","marketplaces","thedotmack"),ye=(0,b.join)(I,"logs"),Qe=(0,b.join)(I,"settings.json"),ee=(0,b.join)(I,"claude-mem.db"),ve=(0,b.join)(I,"observer-sessions"),j=(0,b.basename)(ve);function se(i){(0,U.mkdirSync)(i,{recursive:!0})}var H={dataDir:()=>I,workerPid:()=>(0,b.join)(I,"worker.pid"),serverPid:()=>(0,b.join)(I,".server-beta.pid"),serverPort:()=>(0,b.join)(I,".server-beta.port"),serverRuntime:()=>(0,b.join)(I,".server-beta.runtime.json"),settings:()=>(0,b.join)(I,"settings.json"),database:()=>(0,b.join)(I,"claude-mem.db"),chroma:()=>(0,b.join)(I,"chroma"),combinedCerts:()=>(0,b.join)(I,"combined_certs.pem"),transcriptsConfig:()=>(0,b.join)(I,"transcript-watch.json"),transcriptsState:()=>(0,b.join)(I,"transcript-watch-state.json"),corpora:()=>(0,b.join)(I,"corpora"),supervisorRegistry:()=>(0,b.join)(I,"supervisor.json"),envFile:()=>(0,b.join)(I,".env"),logsDir:()=>ye};var v=require("fs"),te=require("path");var q=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r[r.SILENT=4]="SILENT",r))(q||{}),W=null,V=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=H.logsDir();(0,v.existsSync)(e)||(0,v.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,te.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=H.settings();if((0,v.existsSync)(e)){let t=(0,v.readFileSync)(e,"utf-8"),n=(X(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=q[n]??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}
|
|
3
|
+
${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 s=t;if(typeof t=="string")try{s=JSON.parse(t)}catch{s=t}if(e==="Bash"&&s.command)return`${e}(${s.command})`;if(s.file_path)return`${e}(${s.file_path})`;if(s.notebook_path)return`${e}(${s.notebook_path})`;if(e==="Glob"&&s.pattern)return`${e}(${s.pattern})`;if(e==="Grep"&&s.pattern)return`${e}(${s.pattern})`;if(s.url)return`${e}(${s.url})`;if(s.query)return`${e}(${s.query})`;if(e==="Task"){if(s.subagent_type)return`${e}(${s.subagent_type})`;if(s.description)return`${e}(${s.description})`}return e==="Skill"&&s.skill?`${e}(${s.skill})`:e==="LSP"&&s.operation?`${e}(${s.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),r=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),_=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${s}-${n} ${r}:${o}:${a}.${_}`}log(e,t,s,n,r){if(e<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=q[e].padEnd(5),_=t.padEnd(6),u="";n?.correlationId?u=`[${n.correlationId}] `:n?.sessionId&&(u=`[session-${n.sessionId}] `);let c="";if(r!=null)if(r instanceof Error)c=this.getLevel()===0?`
|
|
4
4
|
${r.message}
|
|
5
5
|
${r.stack}`:` ${r.message}`;else if(this.getLevel()===0&&typeof r=="object")try{c=`
|
|
6
|
-
`+JSON.stringify(r,null,2)}catch{c=" "+this.formatData(r)}else c=" "+this.formatData(r);let l="";if(n){let{sessionId:
|
|
7
|
-
`,"utf8")}catch(
|
|
8
|
-
${
|
|
9
|
-
`)}else
|
|
10
|
-
`)}debug(e,t,s,n){this.log(0,e,t,s,n)}info(e,t,s,n){this.log(1,e,t,s,n)}warn(e,t,s,n){this.log(2,e,t,s,n)}setErrorSink(e){
|
|
6
|
+
`+JSON.stringify(r,null,2)}catch{c=" "+this.formatData(r)}else c=" "+this.formatData(r);let l="";if(n){let{sessionId:h,memorySessionId:O,correlationId:N,...T}=n;Object.keys(T).length>0&&(l=` {${Object.entries(T).map(([g,C])=>`${g}=${C}`).join(", ")}}`)}let m=`[${o}] [${a}] [${_}] ${u}${s}${l}${c}`;if(this.logFilePath)try{(0,v.appendFileSync)(this.logFilePath,m+`
|
|
7
|
+
`,"utf8")}catch(h){let O=h instanceof Error?h:new Error(String(h));k(`[LOGGER] Failed to write to log file: ${O.message}
|
|
8
|
+
${O.stack??""}
|
|
9
|
+
`)}else k(m+`
|
|
10
|
+
`)}debug(e,t,s,n){this.log(0,e,t,s,n)}info(e,t,s,n){this.log(1,e,t,s,n)}warn(e,t,s,n){this.log(2,e,t,s,n)}setErrorSink(e){W=e}error(e,t,s,n){this.log(3,e,t,s,n),this.routeErrorToSink(t,s,n)}routeErrorToSink(e,t,s){try{if(!W||!(s instanceof Error))return;W(s)}catch{}}dataIn(e,t,s,n){this.info(e,`\u2192 ${t}`,s,n)}dataOut(e,t,s,n){this.info(e,`\u2190 ${t}`,s,n)}success(e,t,s,n){this.info(e,`\u2713 ${t}`,s,n)}failure(e,t,s,n){this.error(e,`\u2717 ${t}`,s,n)}},d=new V;var ne=require("crypto");function re(i,e,t){return(0,ne.createHash)("sha256").update([i||"",e||"",t||""].join("\0")).digest("hex").slice(0,16)}var p="claude";function Ce(i){return i.trim().toLowerCase().replace(/\s+/g,"-")}function L(i){if(!i)return p;let e=Ce(i);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:p}function oe(i){let e=["claude","codex","cursor"];return[...i].sort((t,s)=>{let n=e.indexOf(t),r=e.indexOf(s);return n!==-1||r!==-1?n===-1?1:r===-1?-1:n-r:t.localeCompare(s)})}function ie(i,e,t,s,n){let r=Date.now()-s,o=n!==void 0?"up.session_db_id = ?":"up.content_session_id = ?",a=n??e;return i.prepare(`
|
|
11
11
|
SELECT
|
|
12
12
|
up.*,
|
|
13
13
|
s.memory_session_id,
|
|
@@ -20,13 +20,13 @@ ${I.stack??""}
|
|
|
20
20
|
AND up.created_at_epoch >= ?
|
|
21
21
|
ORDER BY up.created_at_epoch DESC
|
|
22
22
|
LIMIT 1
|
|
23
|
-
`).get(a,t,r)??void 0}var
|
|
23
|
+
`).get(a,t,r)??void 0}var _e=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],ae=new RegExp(`<(${_e.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var de=100;function De(i){let e=Object.fromEntries(_e.map(n=>[n,0]));ae.lastIndex=0;let t=0,s=i.replace(ae,(n,r)=>(e[r]=(e[r]??0)+1,t+=1,""));return t>de&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:de,contentLength:i.length}),{stripped:s.trim(),counts:e}}function ue(i){return De(i).stripped}var Ue=["task-notification"],ds=new RegExp(`^\\s*<(${Ue.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),_s=256*1024;var Y=4e3;function P(i){let e=i.trim(),s=ue(i).trim()||e;return s.length<=Y?s:(d.debug("DB","Truncated stored prompt text to the configured cap",{originalLength:s.length,storedLength:Y}),`${s.slice(0,Y-1)}\u2026`)}var we=require("bun:sqlite");var Me=5e3,xe=4194304;function Fe(i){return i.prepare(`
|
|
24
24
|
SELECT name
|
|
25
25
|
FROM sqlite_master
|
|
26
26
|
WHERE type = 'table'
|
|
27
27
|
AND name NOT LIKE 'sqlite_%'
|
|
28
28
|
LIMIT 1
|
|
29
|
-
`).get()!=null}function w(i,e,t){try{i.run(e)}catch(s){let n=s instanceof Error?s:new Error(String(s));throw d.warn("DB",`Failed to apply SQLite pragma ${t}`,{sql:e},n),s}}function
|
|
29
|
+
`).get()!=null}function w(i,e,t){try{i.run(e)}catch(s){let n=s instanceof Error?s:new Error(String(s));throw d.warn("DB",`Failed to apply SQLite pragma ${t}`,{sql:e},n),s}}function ce(i,e={}){let{enableWal:t=!0,enableIncrementalAutoVacuum:s=!0}=e;w(i,`PRAGMA busy_timeout = ${Me}`,"busy_timeout"),w(i,"PRAGMA foreign_keys = ON","foreign_keys"),w(i,"PRAGMA synchronous = NORMAL","synchronous"),w(i,`PRAGMA journal_size_limit = ${xe}`,"journal_size_limit"),s&&!Fe(i)&&w(i,"PRAGMA auto_vacuum = INCREMENTAL","auto_vacuum"),t&&w(i,"PRAGMA journal_mode = WAL","journal_mode")}var pe=4096;var ke=new Set(["set_title","set_prompt_session","remap_project"]),Xe=/^(?:0|[1-9][0-9]*)$/,le=18446744073709551615n;function y(i){throw d.debug("CLOUD_SYNC","Rejected invalid canonical content",{reason:i}),new Error(`canonical content: ${i}`)}function G(i,e={}){return typeof i!="string"||!Xe.test(i)?y("decimal values must be unsigned base-10 strings without leading zeroes"):(BigInt(i)>le&&y("decimal value exceeds uint64"),e.positive&&i==="0"&&y("decimal value must be positive"),i)}function me(i){let e=G(i);return BigInt(e)===le&&y("uint64 sequence overflow"),(BigInt(e)+1n).toString(10)}function Pe(i){(i===null||typeof i!="object"||Array.isArray(i))&&y("mutation must be an object");let e=i;if((typeof e.op!="string"||!ke.has(e.op))&&y("unsupported mutation op"),e.op==="set_title"){let r=x(e,["fields","op","target"],"set_title"),o=B(r.target,["content_session_id","memory_session_id","platform_source"],"set_title.target");o.memory_session_id===void 0&&o.content_session_id===void 0&&y("set_title target requires a session identifier");for(let _ of["memory_session_id","content_session_id","platform_source"])o[_]!==void 0&&D(o[_],_);let a=x(r.fields,["custom_title"],"set_title.fields");D(a.custom_title,"custom_title");return}if(e.op==="set_prompt_session"){let r=x(e,["fields","op","target"],"set_prompt_session"),o=x(r.target,["origin_device_id","origin_local_id"],"set_prompt_session.target");Be(o.origin_device_id),G(o.origin_local_id);let a=B(r.fields,["content_session_id","memory_session_id","platform_source","project"],"set_prompt_session.fields");D(a.memory_session_id,"memory_session_id");for(let _ of["content_session_id","platform_source","project"])a[_]!==void 0&&D(a[_],_);return}let t=x(e,["fields","op","where"],"remap_project"),s=B(t.where,["memory_session_id","merged_into_project_is_null","project"],"remap_project.where");s.project!==void 0&&D(s.project,"project"),s.memory_session_id!==void 0&&D(s.memory_session_id,"memory_session_id"),s.merged_into_project_is_null!==void 0&&s.merged_into_project_is_null!==!0&&y("merged_into_project_is_null may only be true"),Object.keys(s).length===0&&y("remap_project where is empty");let n=B(t.fields,["merged_into_project","project"],"remap_project.fields");n.project!==void 0&&D(n.project,"project"),n.merged_into_project!==void 0&&D(n.merged_into_project,"merged_into_project"),Object.keys(n).length===0&&y("remap_project fields are empty")}function K(i){Pe(i)}function Be(i){return typeof i!="string"||i.length===0||Buffer.byteLength(i,"utf8")>128?y("origin_device_id must be a non-empty string of at most 128 UTF-8 bytes"):i}function D(i,e){return typeof i!="string"||i.length===0||i.trim().length===0||Buffer.byteLength(i,"utf8")>pe?y(`${e} must be a non-blank string of at most ${pe} UTF-8 bytes`):i}function x(i,e,t){if(i===null||typeof i!="object"||Array.isArray(i))return y(`${t} must be an object`);let s=i,n=Object.keys(s).sort(),r=[...e].sort();return(n.length!==r.length||n.some((o,a)=>o!==r[a]))&&y(`${t} must contain exactly: ${r.join(", ")}`),s}function B(i,e,t){if(i===null||typeof i!="object"||Array.isArray(i))return y(`${t} must be an object`);let s=i,n=new Set(e),r=Object.keys(s).find(o=>!n.has(o));return r&&y(`${t} contains unknown field ${r}`),s}var Q=class{db;constructor(e=ee){e instanceof J.Database?this.db=e:(e!==":memory:"&&se(I),this.db=new J.Database(e)),ce(this.db),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable(),this.ensureDiscoveryTokensColumn(),this.createPendingMessagesTable(),this.renameSessionIdColumns(),this.addFailedAtEpochColumn(),this.addOnUpdateCascadeToForeignKeys(),this.addObservationContentHashColumn(),this.addSessionCustomTitleColumn(),this.addSessionPlatformSourceColumn(),this.addObservationModelColumns(),this.ensureMergedIntoProjectColumns(),this.addObservationSubagentColumns(),this.addObservationsUniqueContentHashIndex(),this.addObservationsMetadataColumn(),this.dropDeadPendingMessagesColumns(),this.ensurePendingMessagesToolUseIdColumn(),this.dropWorkerPidColumn(),this.ensureSDKSessionsPlatformContentIdentity(),this.ensureUserPromptsSessionDbId(),this.ensurePendingMessagesSessionToolUniqueIndex(),this.ensureSyncedAtColumns(),this.ensureSyncOriginColumns(),this.ensureSyncOutbox(),this.ensureSyncEntityLedger(),this.ensureSyncRevisionTextAffinity(),this.initializeSyncHubLaunchBaseline()}getIndexColumns(e){return this.db.query(`PRAGMA index_info(${JSON.stringify(e)})`).all().map(t=>t.name)}hasUniqueIndexOnColumns(e,t){return this.db.query(`PRAGMA index_list(${e})`).all().some(n=>{if(n.unique!==1)return!1;let r=this.getIndexColumns(n.name);return r.length===t.length&&r.every((o,a)=>o===t[a])})}resolvePromptSessionDbId(e,t,s){if(t!==void 0)return t;let n=s?L(s):void 0;return n?this.db.prepare(`
|
|
30
30
|
SELECT id
|
|
31
31
|
FROM sdk_sessions
|
|
32
32
|
WHERE COALESCE(NULLIF(platform_source, ''), ?) = ?
|
|
@@ -179,7 +179,7 @@ ${I.stack??""}
|
|
|
179
179
|
typeof(${o.column}) AS storage_type,
|
|
180
180
|
CAST(${o.column} AS TEXT) AS revision
|
|
181
181
|
FROM ${o.table}
|
|
182
|
-
`).iterate()){let l=c;if(l.storage_type==="real")throw new Error(`schema v46: ${o.table}.${o.column} row ${l.row_id} is REAL and unrecoverably rounded`);if(l.storage_type!=="integer"&&l.storage_type!=="text")throw new Error(`schema v46: ${o.table}.${o.column} row ${l.row_id} has unsupported ${l.storage_type} storage`);try{
|
|
182
|
+
`).iterate()){let l=c;if(l.storage_type==="real")throw new Error(`schema v46: ${o.table}.${o.column} row ${l.row_id} is REAL and unrecoverably rounded`);if(l.storage_type!=="integer"&&l.storage_type!=="text")throw new Error(`schema v46: ${o.table}.${o.column} row ${l.row_id} has unsupported ${l.storage_type} storage`);try{G(l.revision,{positive:!0})}catch{throw new Error(`schema v46: ${o.table}.${o.column} row ${l.row_id} is not a positive canonical uint64 revision`)}}if(s(_))continue;if(a.some(c=>c.name===o.temporary))throw new Error(`schema v46: unexpected temporary column ${o.table}.${o.temporary}`);this.db.run(`ALTER TABLE ${o.table} ADD COLUMN ${o.temporary} TEXT NOT NULL DEFAULT '1'`),this.db.run(`UPDATE ${o.table} SET ${o.temporary} = CAST(${o.column} AS TEXT)`);let u=this.db.prepare(`
|
|
183
183
|
SELECT CAST(id AS TEXT) AS row_id
|
|
184
184
|
FROM ${o.table}
|
|
185
185
|
WHERE ${o.temporary} <> CAST(${o.column} AS TEXT)
|
|
@@ -436,7 +436,7 @@ ${I.stack??""}
|
|
|
436
436
|
created_at_epoch INTEGER NOT NULL,
|
|
437
437
|
FOREIGN KEY (session_db_id) REFERENCES sdk_sessions(id) ON DELETE CASCADE
|
|
438
438
|
)
|
|
439
|
-
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_session ON pending_messages(session_db_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_status ON pending_messages(status)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_claude_session ON pending_messages(content_session_id)"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(16,new Date().toISOString()),d.debug("DB","pending_messages table created successfully")}renameSessionIdColumns(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(17))return;d.debug("DB","Checking session ID columns for semantic clarity rename");let t=0,s=(n,r,o)=>{let a=this.db.query(`PRAGMA table_info(${n})`).all(),_=a.some(c=>c.name===r);return a.some(c=>c.name===o)?!1:_?(this.db.run(`ALTER TABLE ${n} RENAME COLUMN ${r} TO ${o}`),d.debug("DB",`Renamed ${n}.${r} to ${o}`),!0):(d.warn("DB",`Column ${r} not found in ${n}, skipping rename`),!1)};s("sdk_sessions","claude_session_id","content_session_id")&&t++,s("sdk_sessions","sdk_session_id","memory_session_id")&&t++,s("pending_messages","claude_session_id","content_session_id")&&t++,s("observations","sdk_session_id","memory_session_id")&&t++,s("session_summaries","sdk_session_id","memory_session_id")&&t++,s("user_prompts","claude_session_id","content_session_id")&&t++,this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(17,new Date().toISOString()),t>0?d.debug("DB",`Successfully renamed ${t} session ID columns`):d.debug("DB","No session ID column renames needed (already up to date)")}addFailedAtEpochColumn(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(20))return;this.db.query("PRAGMA table_info(pending_messages)").all().some(n=>n.name==="failed_at_epoch")||(this.db.run("ALTER TABLE pending_messages ADD COLUMN failed_at_epoch INTEGER"),d.debug("DB","Added failed_at_epoch column to pending_messages table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(20,new Date().toISOString())}addOnUpdateCascadeToForeignKeys(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(21))return;d.debug("DB","Adding ON UPDATE CASCADE to FK constraints on observations and session_summaries"),this.db.run("PRAGMA foreign_keys = OFF"),this.db.run("BEGIN TRANSACTION"),this.db.run("DROP TRIGGER IF EXISTS observations_ai"),this.db.run("DROP TRIGGER IF EXISTS observations_ad"),this.db.run("DROP TRIGGER IF EXISTS observations_au"),this.db.run("DROP TABLE IF EXISTS observations_new");let t=this.db.query("PRAGMA table_info(observations)").all(),s=t.some(
|
|
439
|
+
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_session ON pending_messages(session_db_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_status ON pending_messages(status)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_claude_session ON pending_messages(content_session_id)"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(16,new Date().toISOString()),d.debug("DB","pending_messages table created successfully")}renameSessionIdColumns(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(17))return;d.debug("DB","Checking session ID columns for semantic clarity rename");let t=0,s=(n,r,o)=>{let a=this.db.query(`PRAGMA table_info(${n})`).all(),_=a.some(c=>c.name===r);return a.some(c=>c.name===o)?!1:_?(this.db.run(`ALTER TABLE ${n} RENAME COLUMN ${r} TO ${o}`),d.debug("DB",`Renamed ${n}.${r} to ${o}`),!0):(d.warn("DB",`Column ${r} not found in ${n}, skipping rename`),!1)};s("sdk_sessions","claude_session_id","content_session_id")&&t++,s("sdk_sessions","sdk_session_id","memory_session_id")&&t++,s("pending_messages","claude_session_id","content_session_id")&&t++,s("observations","sdk_session_id","memory_session_id")&&t++,s("session_summaries","sdk_session_id","memory_session_id")&&t++,s("user_prompts","claude_session_id","content_session_id")&&t++,this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(17,new Date().toISOString()),t>0?d.debug("DB",`Successfully renamed ${t} session ID columns`):d.debug("DB","No session ID column renames needed (already up to date)")}addFailedAtEpochColumn(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(20))return;this.db.query("PRAGMA table_info(pending_messages)").all().some(n=>n.name==="failed_at_epoch")||(this.db.run("ALTER TABLE pending_messages ADD COLUMN failed_at_epoch INTEGER"),d.debug("DB","Added failed_at_epoch column to pending_messages table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(20,new Date().toISOString())}addOnUpdateCascadeToForeignKeys(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(21))return;d.debug("DB","Adding ON UPDATE CASCADE to FK constraints on observations and session_summaries"),this.db.run("PRAGMA foreign_keys = OFF"),this.db.run("BEGIN TRANSACTION"),this.db.run("DROP TRIGGER IF EXISTS observations_ai"),this.db.run("DROP TRIGGER IF EXISTS observations_ad"),this.db.run("DROP TRIGGER IF EXISTS observations_au"),this.db.run("DROP TABLE IF EXISTS observations_new");let t=this.db.query("PRAGMA table_info(observations)").all(),s=t.some(f=>f.name==="metadata"),n=t.some(f=>f.name==="content_hash"),r=s?`,
|
|
440
440
|
metadata TEXT`:"",o=s?", metadata":"",a=n?`,
|
|
441
441
|
content_hash TEXT`:"",_=n?", content_hash":"",u=`
|
|
442
442
|
CREATE TABLE observations_new (
|
|
@@ -486,7 +486,7 @@ ${I.stack??""}
|
|
|
486
486
|
INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts)
|
|
487
487
|
VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts);
|
|
488
488
|
END;
|
|
489
|
-
`;this.db.run("DROP TRIGGER IF EXISTS session_summaries_ai"),this.db.run("DROP TRIGGER IF EXISTS session_summaries_ad"),this.db.run("DROP TRIGGER IF EXISTS session_summaries_au"),this.db.run("DROP TABLE IF EXISTS session_summaries_new");let
|
|
489
|
+
`;this.db.run("DROP TRIGGER IF EXISTS session_summaries_ai"),this.db.run("DROP TRIGGER IF EXISTS session_summaries_ad"),this.db.run("DROP TRIGGER IF EXISTS session_summaries_au"),this.db.run("DROP TABLE IF EXISTS session_summaries_new");let h=`
|
|
490
490
|
CREATE TABLE session_summaries_new (
|
|
491
491
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
492
492
|
memory_session_id TEXT NOT NULL,
|
|
@@ -505,17 +505,17 @@ ${I.stack??""}
|
|
|
505
505
|
created_at_epoch INTEGER NOT NULL,
|
|
506
506
|
FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE ON UPDATE CASCADE
|
|
507
507
|
)
|
|
508
|
-
`,
|
|
508
|
+
`,O=`
|
|
509
509
|
INSERT INTO session_summaries_new
|
|
510
510
|
SELECT id, memory_session_id, project, request, investigated, learned,
|
|
511
511
|
completed, next_steps, files_read, files_edited, notes,
|
|
512
512
|
prompt_number, discovery_tokens, created_at, created_at_epoch
|
|
513
513
|
FROM session_summaries
|
|
514
|
-
`,
|
|
514
|
+
`,N=`
|
|
515
515
|
CREATE INDEX idx_session_summaries_sdk_session ON session_summaries(memory_session_id);
|
|
516
516
|
CREATE INDEX idx_session_summaries_project ON session_summaries(project);
|
|
517
517
|
CREATE INDEX idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
|
|
518
|
-
`,
|
|
518
|
+
`,T=`
|
|
519
519
|
CREATE TRIGGER IF NOT EXISTS session_summaries_ai AFTER INSERT ON session_summaries BEGIN
|
|
520
520
|
INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
|
|
521
521
|
VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes);
|
|
@@ -532,7 +532,7 @@ ${I.stack??""}
|
|
|
532
532
|
INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
|
|
533
533
|
VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes);
|
|
534
534
|
END;
|
|
535
|
-
`;try{this.recreateObservationsWithCascade(u,c,l,m),this.recreateSessionSummariesWithCascade(
|
|
535
|
+
`;try{this.recreateObservationsWithCascade(u,c,l,m),this.recreateSessionSummariesWithCascade(h,O,N,T),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(21,new Date().toISOString()),this.db.run("COMMIT"),this.db.run("PRAGMA foreign_keys = ON"),d.debug("DB","Successfully added ON UPDATE CASCADE to FK constraints")}catch(f){throw this.db.run("ROLLBACK"),this.db.run("PRAGMA foreign_keys = ON"),f instanceof Error?f:new Error(String(f))}}recreateObservationsWithCascade(e,t,s,n){this.db.run(e),this.db.run(t),this.db.run("DROP TABLE observations"),this.db.run("ALTER TABLE observations_new RENAME TO observations"),this.db.run(s),this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='observations_fts'").all().length>0&&this.db.run(n)}recreateSessionSummariesWithCascade(e,t,s,n){this.db.run(e),this.db.run(t),this.db.run("DROP TABLE session_summaries"),this.db.run("ALTER TABLE session_summaries_new RENAME TO session_summaries"),this.db.run(s),this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='session_summaries_fts'").all().length>0&&this.db.run(n)}addObservationContentHashColumn(){if(this.db.query("PRAGMA table_info(observations)").all().some(s=>s.name==="content_hash")){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(22,new Date().toISOString());return}this.db.run("ALTER TABLE observations ADD COLUMN content_hash TEXT"),this.db.run("UPDATE observations SET content_hash = substr(hex(randomblob(8)), 1, 16) WHERE content_hash IS NULL"),this.db.run("CREATE INDEX IF NOT EXISTS idx_observations_content_hash ON observations(content_hash, created_at_epoch)"),d.debug("DB","Added content_hash column to observations table with backfill and index"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(22,new Date().toISOString())}addSessionCustomTitleColumn(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(23),s=this.db.query("PRAGMA table_info(sdk_sessions)").all().some(n=>n.name==="custom_title");e&&s||(s||(this.db.run("ALTER TABLE sdk_sessions ADD COLUMN custom_title TEXT"),d.debug("DB","Added custom_title column to sdk_sessions table")),e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(23,new Date().toISOString()))}addSessionPlatformSourceColumn(){let t=this.db.query("PRAGMA table_info(sdk_sessions)").all().some(o=>o.name==="platform_source"),n=this.db.query("PRAGMA index_list(sdk_sessions)").all().some(o=>o.name==="idx_sdk_sessions_platform_source");this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(24)&&t&&n||(t||(this.db.run(`ALTER TABLE sdk_sessions ADD COLUMN platform_source TEXT NOT NULL DEFAULT '${p}'`),d.debug("DB","Added platform_source column to sdk_sessions table")),this.db.run(`
|
|
536
536
|
UPDATE sdk_sessions
|
|
537
537
|
SET platform_source = '${p}'
|
|
538
538
|
WHERE platform_source IS NULL OR platform_source = ''
|
|
@@ -586,16 +586,16 @@ ${I.stack??""}
|
|
|
586
586
|
UPDATE sdk_sessions
|
|
587
587
|
SET memory_session_id = ?
|
|
588
588
|
WHERE id = ?
|
|
589
|
-
`).run(t,e),t&&this.requeuePromptSync(e)}enqueueMutationOp(e,t){let s=JSON.parse(JSON.stringify(t));if(s.op==="set_prompt_session"){let n=s.target;n?.origin_device_id===null&&(n.origin_device_id="self")}
|
|
589
|
+
`).run(t,e),t&&this.requeuePromptSync(e)}enqueueMutationOp(e,t){let s=JSON.parse(JSON.stringify(t));if(s.op==="set_prompt_session"){let n=s.target;n?.origin_device_id===null&&(n.origin_device_id="self")}K(s),this.db.prepare(`
|
|
590
590
|
INSERT INTO sync_outbox (op_uuid, rev, body, created_at_epoch)
|
|
591
591
|
VALUES (?, ?, ?, ?)
|
|
592
|
-
`).run((0,
|
|
592
|
+
`).run((0,Ee.randomUUID)(),String(e),JSON.stringify(t),Date.now())}requeuePromptSync(e){let t=this.db.prepare(`
|
|
593
593
|
SELECT memory_session_id, project, content_session_id, platform_source
|
|
594
594
|
FROM sdk_sessions WHERE id = ?
|
|
595
595
|
`).get(e);if(!t?.memory_session_id)return;this.db.transaction(()=>{let n=this.db.prepare(`
|
|
596
596
|
SELECT CAST(id AS TEXT) AS id, CAST(sync_rev AS TEXT) AS sync_rev FROM user_prompts
|
|
597
597
|
WHERE session_db_id = ? AND origin_device_id IS NULL
|
|
598
|
-
`).all(e);if(n.length!==0)for(let r of n){let o=
|
|
598
|
+
`).all(e);if(n.length!==0)for(let r of n){let o=me(r.sync_rev);this.db.prepare(`
|
|
599
599
|
UPDATE user_prompts SET sync_rev = ?, synced_at = NULL
|
|
600
600
|
WHERE id = ? AND origin_device_id IS NULL
|
|
601
601
|
`).run(o,r.id),this.enqueueMutationOp(o,{op:"set_prompt_session",target:{origin_device_id:null,origin_local_id:r.id},fields:{memory_session_id:t.memory_session_id,project:t.project,content_session_id:t.content_session_id,platform_source:t.platform_source}})}})()}markSessionCompleted(e){let t=Date.now(),s=new Date(t).toISOString();this.db.prepare(`
|
|
@@ -613,7 +613,7 @@ ${I.stack??""}
|
|
|
613
613
|
FROM sdk_sessions
|
|
614
614
|
WHERE project IS NOT NULL AND project != ''
|
|
615
615
|
AND project != ?
|
|
616
|
-
`,n=[
|
|
616
|
+
`,n=[j];return t&&(s+=" AND COALESCE(platform_source, ?) = ?",n.push(p,t)),s+=" ORDER BY project ASC",this.db.prepare(s).all(...n).map(o=>o.project)}getProjectCatalog(){let e=this.db.prepare(`
|
|
617
617
|
SELECT
|
|
618
618
|
COALESCE(platform_source, '${p}') as platform_source,
|
|
619
619
|
project,
|
|
@@ -623,7 +623,7 @@ ${I.stack??""}
|
|
|
623
623
|
AND project != ?
|
|
624
624
|
GROUP BY COALESCE(platform_source, '${p}'), project
|
|
625
625
|
ORDER BY latest_epoch DESC
|
|
626
|
-
`).all(
|
|
626
|
+
`).all(j),t=[],s=new Set,n={};for(let o of e){let a=L(o.platform_source);n[a]||(n[a]=[]),n[a].includes(o.project)||n[a].push(o.project),s.has(o.project)||(s.add(o.project),t.push(o.project))}let r=oe(Object.keys(n));return{projects:t,sources:r,projectsBySource:Object.fromEntries(r.map(o=>[o,n[o]||[]]))}}getLatestUserPrompt(e,t){let s=this.resolvePromptSessionDbId(e,t),n=s!==null?"up.session_db_id = ?":"up.content_session_id = ?",r=s!==null?s:e;return this.db.prepare(`
|
|
627
627
|
SELECT
|
|
628
628
|
up.*,
|
|
629
629
|
s.memory_session_id,
|
|
@@ -634,7 +634,7 @@ ${I.stack??""}
|
|
|
634
634
|
WHERE ${n}
|
|
635
635
|
ORDER BY up.created_at_epoch DESC
|
|
636
636
|
LIMIT 1
|
|
637
|
-
`).get(r)}findRecentDuplicateUserPrompt(e,t,s,n){return
|
|
637
|
+
`).get(r)}findRecentDuplicateUserPrompt(e,t,s,n){return ie(this.db,e,P(t),s,this.resolvePromptSessionDbId(e,n)??void 0)}getRecentSessionsWithStatus(e,t=3,s){let n=[e],r="";return s&&(r=`AND COALESCE(NULLIF(s.platform_source, ''), '${p}') = ?`,n.push(L(s))),n.push(t),this.db.prepare(`
|
|
638
638
|
SELECT * FROM (
|
|
639
639
|
SELECT
|
|
640
640
|
s.memory_session_id,
|
|
@@ -675,14 +675,14 @@ ${I.stack??""}
|
|
|
675
675
|
SELECT *
|
|
676
676
|
FROM observations
|
|
677
677
|
WHERE id = ?
|
|
678
|
-
`).get(e)||null}getObservationsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:r,platformSource:o,type:a,concepts:_,files:u}=t,c=s==="relevance",l=c?"":`ORDER BY o.created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,m=n&&!c?`LIMIT ${n}`:"",
|
|
678
|
+
`).get(e)||null}getObservationsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:r,platformSource:o,type:a,concepts:_,files:u}=t,c=s==="relevance",l=c?"":`ORDER BY o.created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,m=n&&!c?`LIMIT ${n}`:"",h=e.map(()=>"?").join(","),O=[...e],N=[];if(r&&(N.push("(o.project = ? OR o.merged_into_project = ?)"),O.push(r,r)),o&&(N.push(`COALESCE(NULLIF(s.platform_source, ''), '${p}') = ?`),O.push(L(o))),a)if(Array.isArray(a)){let R=a.map(()=>"?").join(",");N.push(`o.type IN (${R})`),O.push(...a)}else N.push("o.type = ?"),O.push(a);if(_){let R=Array.isArray(_)?_:[_],S=R.map(()=>"EXISTS (SELECT 1 FROM json_each(o.concepts) WHERE value = ?)");O.push(...R),N.push(`(${S.join(" OR ")})`)}if(u){let R=Array.isArray(u)?u:[u],S=R.map(()=>"(EXISTS (SELECT 1 FROM json_each(o.files_read) WHERE value LIKE ?) OR EXISTS (SELECT 1 FROM json_each(o.files_modified) WHERE value LIKE ?))");R.forEach(A=>{O.push(`%${A}%`,`%${A}%`)}),N.push(`(${S.join(" OR ")})`)}let T=N.length>0?`WHERE o.id IN (${h}) AND ${N.join(" AND ")}`:`WHERE o.id IN (${h})`,g=this.db.prepare(`
|
|
679
679
|
SELECT o.*
|
|
680
680
|
FROM observations o
|
|
681
681
|
LEFT JOIN sdk_sessions s ON s.memory_session_id = o.memory_session_id
|
|
682
|
-
${
|
|
682
|
+
${T}
|
|
683
683
|
${l}
|
|
684
684
|
${m}
|
|
685
|
-
`).all(...
|
|
685
|
+
`).all(...O);if(!c)return g;let C=new Map(g.map(R=>[R.id,R])),E=e.map(R=>C.get(R)).filter(R=>!!R);return n?E.slice(0,n):E}getSummaryForSession(e,t){let s=[e],n="";return t&&(n=`
|
|
686
686
|
AND EXISTS (
|
|
687
687
|
SELECT 1
|
|
688
688
|
FROM sdk_sessions sdk
|
|
@@ -718,7 +718,7 @@ ${I.stack??""}
|
|
|
718
718
|
SELECT COUNT(*) as count FROM user_prompts WHERE session_db_id = ?
|
|
719
719
|
`).get(s).count:this.db.prepare(`
|
|
720
720
|
SELECT COUNT(*) as count FROM user_prompts WHERE content_session_id = ?
|
|
721
|
-
`).get(e).count}createSDKSession(e,t,s,n,r){let o=new Date,a=o.getTime(),_=r?L(r):p,u=
|
|
721
|
+
`).get(e).count}createSDKSession(e,t,s,n,r){let o=new Date,a=o.getTime(),_=r?L(r):p,u=P(s);n&&this.validateSetTitleMutation(e,_,n);let c=this.db.prepare(`
|
|
722
722
|
SELECT id, platform_source
|
|
723
723
|
FROM sdk_sessions
|
|
724
724
|
WHERE COALESCE(NULLIF(platform_source, ''), ?) = ?
|
|
@@ -733,7 +733,7 @@ ${I.stack??""}
|
|
|
733
733
|
INSERT INTO sdk_sessions
|
|
734
734
|
(content_session_id, memory_session_id, project, platform_source, user_prompt, custom_title, started_at, started_at_epoch, status)
|
|
735
735
|
VALUES (?, NULL, ?, ?, ?, ?, ?, ?, 'active')
|
|
736
|
-
`).run(e,t,_,u,n||null,o.toISOString(),a);return n&&this.enqueueSetTitleOp(e,_,n),Number(l.lastInsertRowid)}enqueueSetTitleOp(e,t,s){let n=this.validateSetTitleMutation(e,t,s);this.enqueueMutationOp("1",n)}validateSetTitleMutation(e,t,s){let n={op:"set_title",target:{content_session_id:e,platform_source:t},fields:{custom_title:s}};return
|
|
736
|
+
`).run(e,t,_,u,n||null,o.toISOString(),a);return n&&this.enqueueSetTitleOp(e,_,n),Number(l.lastInsertRowid)}enqueueSetTitleOp(e,t,s){let n=this.validateSetTitleMutation(e,t,s);this.enqueueMutationOp("1",n)}validateSetTitleMutation(e,t,s){let n={op:"set_title",target:{content_session_id:e,platform_source:t},fields:{custom_title:s}};return K(n),n}saveUserPrompt(e,t,s,n){let r=new Date,o=r.getTime(),a=P(s),_=this.resolvePromptSessionDbId(e,n);return this.db.prepare(`
|
|
737
737
|
INSERT INTO user_prompts
|
|
738
738
|
(session_db_id, content_session_id, prompt_number, prompt_text, created_at, created_at_epoch)
|
|
739
739
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
@@ -752,7 +752,7 @@ ${I.stack??""}
|
|
|
752
752
|
(memory_session_id, project, request, investigated, learned, completed,
|
|
753
753
|
next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
|
|
754
754
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
755
|
-
`).run(e,t,s.request,s.investigated,s.learned,s.completed,s.next_steps,s.notes,n||null,r,_,a);return{id:Number(c.lastInsertRowid),createdAtEpoch:a}}storeObservations(e,t,s,n,r,o=0,a,_){let u=a??Date.now(),c=new Date(u).toISOString();return this.db.transaction(()=>{let m=[],
|
|
755
|
+
`).run(e,t,s.request,s.investigated,s.learned,s.completed,s.next_steps,s.notes,n||null,r,_,a);return{id:Number(c.lastInsertRowid),createdAtEpoch:a}}storeObservations(e,t,s,n,r,o=0,a,_){let u=a??Date.now(),c=new Date(u).toISOString();return this.db.transaction(()=>{let m=[],h=this.db.prepare(`
|
|
756
756
|
INSERT INTO observations
|
|
757
757
|
(memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
|
|
758
758
|
files_read, files_modified, prompt_number, discovery_tokens, agent_type, agent_id, content_hash, created_at, created_at_epoch,
|
|
@@ -760,19 +760,19 @@ ${I.stack??""}
|
|
|
760
760
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
761
761
|
ON CONFLICT(memory_session_id, content_hash) DO NOTHING
|
|
762
762
|
RETURNING id
|
|
763
|
-
`),
|
|
763
|
+
`),O=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let T of s){let f=re(e,T.title,T.narrative),g=h.get(e,t,T.type,T.title,T.subtitle,JSON.stringify(T.facts),T.narrative,JSON.stringify(T.concepts),JSON.stringify(T.files_read),JSON.stringify(T.files_modified),r||null,o,T.agent_type??null,T.agent_id??null,f,c,u,_||null,T.metadata??null);if(g){m.push(g.id);continue}let C=O.get(e,f);if(!C)throw new Error(`storeObservations: ON CONFLICT without existing row for content_hash=${f}`);m.push(C.id)}let N=null;if(n){let f=this.db.prepare(`
|
|
764
764
|
INSERT INTO session_summaries
|
|
765
765
|
(memory_session_id, project, request, investigated, learned, completed,
|
|
766
766
|
next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
|
|
767
767
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
768
|
-
`).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,r||null,o,c,u);
|
|
768
|
+
`).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,r||null,o,c,u);N=Number(f.lastInsertRowid)}return{observationIds:m,summaryId:N,createdAtEpoch:u}})()}getSessionSummariesByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:r,platformSource:o}=t,a=s==="relevance",_=a?"":`ORDER BY ss.created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,u=n&&!a?`LIMIT ${n}`:"",c=e.map(()=>"?").join(","),l=[...e],m=[];r&&(m.push("(ss.project = ? OR ss.merged_into_project = ?)"),l.push(r,r)),o&&(m.push(`COALESCE(NULLIF(s.platform_source, ''), '${p}') = ?`),l.push(L(o)));let h=m.length>0?`AND ${m.join(" AND ")}`:"",N=this.db.prepare(`
|
|
769
769
|
SELECT ss.*
|
|
770
770
|
FROM session_summaries ss
|
|
771
771
|
LEFT JOIN sdk_sessions s ON s.memory_session_id = ss.memory_session_id
|
|
772
|
-
WHERE ss.id IN (${c}) ${
|
|
772
|
+
WHERE ss.id IN (${c}) ${h}
|
|
773
773
|
${_}
|
|
774
774
|
${u}
|
|
775
|
-
`).all(...l);if(!a)return
|
|
775
|
+
`).all(...l);if(!a)return N;let T=new Map(N.map(g=>[g.id,g])),f=e.map(g=>T.get(g)).filter(g=>!!g);return n?f.slice(0,n):f}getUserPromptsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:r,platformSource:o}=t,a=s==="relevance",_=a?"":`ORDER BY up.created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,u=n&&!a?`LIMIT ${n}`:"",c=e.map(()=>"?").join(","),l=[...e],m=[];r&&(m.push("s.project = ?"),l.push(r)),o&&(m.push(`COALESCE(NULLIF(s.platform_source, ''), '${p}') = ?`),l.push(L(o)));let h=m.length>0?`AND ${m.join(" AND ")}`:"",N=this.db.prepare(`
|
|
776
776
|
SELECT
|
|
777
777
|
up.*,
|
|
778
778
|
s.project,
|
|
@@ -780,56 +780,56 @@ ${I.stack??""}
|
|
|
780
780
|
COALESCE(NULLIF(s.platform_source, ''), '${p}') as platform_source
|
|
781
781
|
FROM user_prompts up
|
|
782
782
|
JOIN sdk_sessions s ON up.session_db_id = s.id
|
|
783
|
-
WHERE up.id IN (${c}) ${
|
|
783
|
+
WHERE up.id IN (${c}) ${h}
|
|
784
784
|
${_}
|
|
785
785
|
${u}
|
|
786
|
-
`).all(...l);if(!a)return
|
|
786
|
+
`).all(...l);if(!a)return N;let T=new Map(N.map(g=>[g.id,g])),f=e.map(g=>T.get(g)).filter(g=>!!g);return n?f.slice(0,n):f}getTimelineAroundTimestamp(e,t=10,s=10,n,r){return this.getTimelineAroundObservation(null,e,t,s,n,r)}getTimelineAroundObservation(e,t,s=10,n=10,r,o){let a=o?L(o):void 0,_=(E,R,S=!1)=>{let A=[],F=[];return r&&(S?(A.push(`(${E}.project = ? OR ${E}.merged_into_project = ?)`),F.push(r,r)):(A.push(`${E}.project = ?`),F.push(r))),a&&(A.push(`COALESCE(NULLIF(${R}.platform_source, ''), '${p}') = ?`),F.push(a)),{clause:A.length>0?`AND ${A.join(" AND ")}`:"",params:F}},u=_("o","src",!0),c=_("ss","src",!0),l=_("s","s"),m,h;if(e!==null){let E=`
|
|
787
787
|
SELECT o.id, o.created_at_epoch
|
|
788
788
|
FROM observations o
|
|
789
789
|
LEFT JOIN sdk_sessions src ON src.memory_session_id = o.memory_session_id
|
|
790
790
|
WHERE o.id <= ? ${u.clause}
|
|
791
791
|
ORDER BY o.id DESC
|
|
792
792
|
LIMIT ?
|
|
793
|
-
`,
|
|
793
|
+
`,R=`
|
|
794
794
|
SELECT o.id, o.created_at_epoch
|
|
795
795
|
FROM observations o
|
|
796
796
|
LEFT JOIN sdk_sessions src ON src.memory_session_id = o.memory_session_id
|
|
797
797
|
WHERE o.id >= ? ${u.clause}
|
|
798
798
|
ORDER BY o.id ASC
|
|
799
799
|
LIMIT ?
|
|
800
|
-
`;try{let
|
|
800
|
+
`;try{let S=this.db.prepare(E).all(e,...u.params,s+1),A=this.db.prepare(R).all(e,...u.params,n+1);if(S.length===0&&A.length===0)return{observations:[],sessions:[],prompts:[]};m=S.length>0?S[S.length-1].created_at_epoch:t,h=A.length>0?A[A.length-1].created_at_epoch:t}catch(S){return S instanceof Error?d.error("DB","Error getting boundary observations",{project:r},S):d.error("DB","Error getting boundary observations with non-Error",{},new Error(String(S))),{observations:[],sessions:[],prompts:[]}}}else{let E=`
|
|
801
801
|
SELECT o.created_at_epoch
|
|
802
802
|
FROM observations o
|
|
803
803
|
LEFT JOIN sdk_sessions src ON src.memory_session_id = o.memory_session_id
|
|
804
804
|
WHERE o.created_at_epoch <= ? ${u.clause}
|
|
805
805
|
ORDER BY o.created_at_epoch DESC
|
|
806
806
|
LIMIT ?
|
|
807
|
-
`,
|
|
807
|
+
`,R=`
|
|
808
808
|
SELECT o.created_at_epoch
|
|
809
809
|
FROM observations o
|
|
810
810
|
LEFT JOIN sdk_sessions src ON src.memory_session_id = o.memory_session_id
|
|
811
811
|
WHERE o.created_at_epoch >= ? ${u.clause}
|
|
812
812
|
ORDER BY o.created_at_epoch ASC
|
|
813
813
|
LIMIT ?
|
|
814
|
-
`;try{let
|
|
814
|
+
`;try{let S=this.db.prepare(E).all(t,...u.params,s),A=this.db.prepare(R).all(t,...u.params,n+1);if(S.length===0&&A.length===0)return{observations:[],sessions:[],prompts:[]};m=S.length>0?S[S.length-1].created_at_epoch:t,h=A.length>0?A[A.length-1].created_at_epoch:t}catch(S){return S instanceof Error?d.error("DB","Error getting boundary timestamps",{project:r},S):d.error("DB","Error getting boundary timestamps with non-Error",{},new Error(String(S))),{observations:[],sessions:[],prompts:[]}}}let O=`
|
|
815
815
|
SELECT o.*
|
|
816
816
|
FROM observations o
|
|
817
817
|
LEFT JOIN sdk_sessions src ON src.memory_session_id = o.memory_session_id
|
|
818
818
|
WHERE o.created_at_epoch >= ? AND o.created_at_epoch <= ? ${u.clause}
|
|
819
819
|
ORDER BY o.created_at_epoch ASC
|
|
820
|
-
`,
|
|
820
|
+
`,N=`
|
|
821
821
|
SELECT ss.*
|
|
822
822
|
FROM session_summaries ss
|
|
823
823
|
LEFT JOIN sdk_sessions src ON src.memory_session_id = ss.memory_session_id
|
|
824
824
|
WHERE ss.created_at_epoch >= ? AND ss.created_at_epoch <= ? ${c.clause}
|
|
825
825
|
ORDER BY ss.created_at_epoch ASC
|
|
826
|
-
`,
|
|
826
|
+
`,T=`
|
|
827
827
|
SELECT up.*, s.project, s.memory_session_id, COALESCE(NULLIF(s.platform_source, ''), '${p}') as platform_source
|
|
828
828
|
FROM user_prompts up
|
|
829
829
|
JOIN sdk_sessions s ON up.session_db_id = s.id
|
|
830
830
|
WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${l.clause}
|
|
831
831
|
ORDER BY up.created_at_epoch ASC
|
|
832
|
-
`,
|
|
832
|
+
`,f=this.db.prepare(O).all(m,h,...u.params),g=this.db.prepare(N).all(m,h,...c.params),C=this.db.prepare(T).all(m,h,...l.params);return{observations:f,sessions:g.map(E=>({id:E.id,memory_session_id:E.memory_session_id,project:E.project,request:E.request,completed:E.completed,next_steps:E.next_steps,created_at:E.created_at,created_at_epoch:E.created_at_epoch})),prompts:C.map(E=>({id:E.id,content_session_id:E.content_session_id,prompt_number:E.prompt_number,prompt_text:E.prompt_text,project:E.project,platform_source:E.platform_source,created_at:E.created_at,created_at_epoch:E.created_at_epoch}))}}getOrCreateManualSession(e){let t=`manual-${e}`,s=`manual-content-${e}`;if(this.db.prepare("SELECT memory_session_id FROM sdk_sessions WHERE memory_session_id = ?").get(t))return t;let r=new Date;return this.db.prepare(`
|
|
833
833
|
INSERT INTO sdk_sessions (memory_session_id, content_session_id, project, platform_source, started_at, started_at_epoch, status)
|
|
834
834
|
VALUES (?, ?, ?, ?, ?, ?, 'active')
|
|
835
835
|
`).run(t,s,e,p,r.toISOString(),r.getTime()),d.info("SESSION","Created manual session",{memorySessionId:t,project:e}),t}close(){this.db.close()}importSdkSession(e){let t=L(e.platform_source),s=this.db.prepare(`SELECT id FROM sdk_sessions
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
var __IMPORT_META_URL__ = require("node:url").pathToFileURL(__filename).href;
|
|
2
|
-
"use strict";var
|
|
3
|
-
${r.stack}`:r.message;if(Array.isArray(r))return`[${r.length} items]`;let e=Object.keys(r);return e.length===0?"{}":e.length<=3?JSON.stringify(r):`{${e.length} keys: ${e.slice(0,3).join(", ")}...}`}return String(r)}formatTool(r,e){if(!e)return r;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{t=e}if(r==="Bash"&&t.command)return`${r}(${t.command})`;if(t.file_path)return`${r}(${t.file_path})`;if(t.notebook_path)return`${r}(${t.notebook_path})`;if(r==="Glob"&&t.pattern)return`${r}(${t.pattern})`;if(r==="Grep"&&t.pattern)return`${r}(${t.pattern})`;if(t.url)return`${r}(${t.url})`;if(t.query)return`${r}(${t.query})`;if(r==="Task"){if(t.subagent_type)return`${r}(${t.subagent_type})`;if(t.description)return`${r}(${t.description})`}return r==="Skill"&&t.skill?`${r}(${t.skill})`:r==="LSP"&&t.operation?`${r}(${t.operation})`:r}formatTimestamp(r){let e=r.getFullYear(),t=String(r.getMonth()+1).padStart(2,"0"),n=String(r.getDate()).padStart(2,"0"),s=String(r.getHours()).padStart(2,"0"),
|
|
2
|
+
"use strict";var v=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var P=(i,r)=>{for(var e in r)v(i,e,{get:r[e],enumerable:!0})},U=(i,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of F(r))!N.call(i,n)&&n!==e&&v(i,n,{get:()=>r[n],enumerable:!(t=w(r,n))||t.enumerable});return i};var M=i=>U(v({},"__esModule",{value:!0}),i);var V={};P(V,{parseFileList:()=>K});module.exports=M(V);var l=require("fs"),T=require("path");var o=require("path"),f=require("os"),u=require("fs"),k=require("url");var B=null;function G(i){return(B??process.stderr.write.bind(process.stderr))(i)}function g(i){G(i)}var tr=process.platform==="win32";function W(i){return i.replace(/^\uFEFF/,"")}function d(i){return JSON.parse(W(i))}function j(){return typeof __dirname<"u"?__dirname:(0,o.dirname)((0,k.fileURLToPath)(__IMPORT_META_URL__))}var or=j();function _(i){return typeof i!="string"||i.length===0?i:i==="~"?(0,f.homedir)():i.startsWith("~/")?(0,o.join)((0,f.homedir)(),i.slice(2)):i}function H(){if(process.env.CLAUDE_MEM_DATA_DIR)return _(process.env.CLAUDE_MEM_DATA_DIR);let i=(0,o.join)((0,f.homedir)(),".claude-mem"),r=(0,o.join)(i,"settings.json");try{if((0,u.existsSync)(r)){let e=d((0,u.readFileSync)(r,"utf-8")),t=e.env??e;if(t.CLAUDE_MEM_DATA_DIR)return _(t.CLAUDE_MEM_DATA_DIR)}}catch{}return i}var c=H(),J=process.env.CLAUDE_CONFIG_DIR||(0,o.join)((0,f.homedir)(),".claude"),sr=(0,o.join)(J,"plugins","marketplaces","thedotmack"),Y=(0,o.join)(c,"logs"),cr=(0,o.join)(c,"settings.json"),lr=(0,o.join)(c,"claude-mem.db"),z=(0,o.join)(c,"observer-sessions"),ar=(0,o.basename)(z);var D={dataDir:()=>c,workerPid:()=>(0,o.join)(c,"worker.pid"),serverPid:()=>(0,o.join)(c,".server-beta.pid"),serverPort:()=>(0,o.join)(c,".server-beta.port"),serverRuntime:()=>(0,o.join)(c,".server-beta.runtime.json"),settings:()=>(0,o.join)(c,"settings.json"),database:()=>(0,o.join)(c,"claude-mem.db"),chroma:()=>(0,o.join)(c,"chroma"),combinedCerts:()=>(0,o.join)(c,"combined_certs.pem"),transcriptsConfig:()=>(0,o.join)(c,"transcript-watch.json"),transcriptsState:()=>(0,o.join)(c,"transcript-watch-state.json"),corpora:()=>(0,o.join)(c,"corpora"),supervisorRegistry:()=>(0,o.join)(c,"supervisor.json"),envFile:()=>(0,o.join)(c,".env"),logsDir:()=>Y};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||{}),$=null,C=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let r=D.logsDir();(0,l.existsSync)(r)||(0,l.mkdirSync)(r,{recursive:!0});let e=new Date().toISOString().split("T")[0];this.logFilePath=(0,T.join)(r,`claude-mem-${e}.log`)}catch(r){console.error("[LOGGER] Failed to initialize log file:",r instanceof Error?r.message:String(r)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let r=D.settings();if((0,l.existsSync)(r)){let e=(0,l.readFileSync)(r,"utf-8"),n=(d(e).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=O[n]??1}else this.level=1}catch(r){console.error("[LOGGER] Failed to load log level from settings:",r instanceof Error?r.message:String(r)),this.level=1}return this.level}formatData(r){if(r==null)return"";if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return r.toString();if(typeof r=="object"){if(r instanceof Error)return this.getLevel()===0?`${r.message}
|
|
3
|
+
${r.stack}`:r.message;if(Array.isArray(r))return`[${r.length} items]`;let e=Object.keys(r);return e.length===0?"{}":e.length<=3?JSON.stringify(r):`{${e.length} keys: ${e.slice(0,3).join(", ")}...}`}return String(r)}formatTool(r,e){if(!e)return r;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{t=e}if(r==="Bash"&&t.command)return`${r}(${t.command})`;if(t.file_path)return`${r}(${t.file_path})`;if(t.notebook_path)return`${r}(${t.notebook_path})`;if(r==="Glob"&&t.pattern)return`${r}(${t.pattern})`;if(r==="Grep"&&t.pattern)return`${r}(${t.pattern})`;if(t.url)return`${r}(${t.url})`;if(t.query)return`${r}(${t.query})`;if(r==="Task"){if(t.subagent_type)return`${r}(${t.subagent_type})`;if(t.description)return`${r}(${t.description})`}return r==="Skill"&&t.skill?`${r}(${t.skill})`:r==="LSP"&&t.operation?`${r}(${t.operation})`:r}formatTimestamp(r){let e=r.getFullYear(),t=String(r.getMonth()+1).padStart(2,"0"),n=String(r.getDate()).padStart(2,"0"),s=String(r.getHours()).padStart(2,"0"),m=String(r.getMinutes()).padStart(2,"0"),S=String(r.getSeconds()).padStart(2,"0"),y=String(r.getMilliseconds()).padStart(3,"0");return`${e}-${t}-${n} ${s}:${m}:${S}.${y}`}log(r,e,t,n,s){if(r<this.getLevel())return;this.ensureLogFileInitialized();let m=this.formatTimestamp(new Date),S=O[r].padEnd(5),y=e.padEnd(6),E="";n?.correlationId?E=`[${n.correlationId}] `:n?.sessionId&&(E=`[session-${n.sessionId}] `);let a="";if(s!=null)if(s instanceof Error)a=this.getLevel()===0?`
|
|
4
4
|
${s.message}
|
|
5
5
|
${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{a=`
|
|
6
|
-
`+JSON.stringify(s,null,2)}catch{a=" "+this.formatData(s)}else a=" "+this.formatData(s);let
|
|
7
|
-
`,"utf8")}catch(p){let
|
|
8
|
-
${
|
|
9
|
-
`)}else
|
|
10
|
-
`)}debug(r,e,t,n){this.log(0,r,e,t,n)}info(r,e,t,n){this.log(1,r,e,t,n)}warn(r,e,t,n){this.log(2,r,e,t,n)}setErrorSink(r){$=r}error(r,e,t,n){this.log(3,r,e,t,n),this.routeErrorToSink(e,t,n)}routeErrorToSink(r,e,t){try{if(!$||!(t instanceof Error))return;$(t)}catch{}}dataIn(r,e,t,n){this.info(r,`\u2192 ${e}`,t,n)}dataOut(r,e,t,n){this.info(r,`\u2190 ${e}`,t,n)}success(r,e,t,n){this.info(r,`\u2713 ${e}`,t,n)}failure(r,e,t,n){this.error(r,`\u2717 ${e}`,t,n)}},I=new C;function
|
|
6
|
+
`+JSON.stringify(s,null,2)}catch{a=" "+this.formatData(s)}else a=" "+this.formatData(s);let x="";if(n){let{sessionId:p,memorySessionId:h,correlationId:q,...L}=n;Object.keys(L).length>0&&(x=` {${Object.entries(L).map(([A,b])=>`${A}=${b}`).join(", ")}}`)}let R=`[${m}] [${S}] [${y}] ${E}${t}${x}${a}`;if(this.logFilePath)try{(0,l.appendFileSync)(this.logFilePath,R+`
|
|
7
|
+
`,"utf8")}catch(p){let h=p instanceof Error?p:new Error(String(p));g(`[LOGGER] Failed to write to log file: ${h.message}
|
|
8
|
+
${h.stack??""}
|
|
9
|
+
`)}else g(R+`
|
|
10
|
+
`)}debug(r,e,t,n){this.log(0,r,e,t,n)}info(r,e,t,n){this.log(1,r,e,t,n)}warn(r,e,t,n){this.log(2,r,e,t,n)}setErrorSink(r){$=r}error(r,e,t,n){this.log(3,r,e,t,n),this.routeErrorToSink(e,t,n)}routeErrorToSink(r,e,t){try{if(!$||!(t instanceof Error))return;$(t)}catch{}}dataIn(r,e,t,n){this.info(r,`\u2192 ${e}`,t,n)}dataOut(r,e,t,n){this.info(r,`\u2190 ${e}`,t,n)}success(r,e,t,n){this.info(r,`\u2713 ${e}`,t,n)}failure(r,e,t,n){this.error(r,`\u2717 ${e}`,t,n)}},I=new C;function K(i){if(!i)return[];try{let r=JSON.parse(i);return Array.isArray(r)?r:[String(r)]}catch(r){return I.debug("DB","File list is not JSON; treating value as a single path",{value:i},r instanceof Error?r:new Error(String(r))),[i]}}0&&(module.exports={parseFileList});
|