claude-mem 13.4.0 → 13.4.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 +333 -304
- package/dist/opencode-plugin/index.js +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +4 -2
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.mcp.json +3 -3
- package/plugin/bun.lock +163 -0
- package/plugin/modes/code.json +16 -16
- package/plugin/package.json +2 -2
- package/plugin/scripts/bun-runner.js +76 -54
- package/plugin/scripts/context-generator.cjs +73 -60
- package/plugin/scripts/mcp-server.cjs +37 -30
- package/plugin/scripts/server-beta-service.cjs +158 -132
- package/plugin/scripts/transcript-watcher.cjs +26 -0
- package/plugin/scripts/version-check.js +125 -1
- package/plugin/scripts/worker-service.cjs +266 -234
- package/plugin/skills/smart-explore/SKILL.md +6 -3
- package/plugin/skills/standup/SKILL.md +157 -0
- package/plugin/skills/standup/agent-brief.md +47 -0
- package/plugin/skills/standup/standup.mjs +662 -0
- package/plugin/ui/viewer-bundle.js +14 -14
|
@@ -1,12 +1,25 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
${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"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),d=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${s}-${n} ${o}:${i}:${a}.${d}`}log(e,t,s,n,o){if(e<this.getLevel())return;this.ensureLogFileInitialized();let i=this.formatTimestamp(new Date),a=ee[e].padEnd(5),d=t.padEnd(6),
|
|
1
|
+
"use strict";var yt=Object.create;var j=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,kt=Object.prototype.hasOwnProperty;var Pt=(r,e)=>{for(var t in e)j(r,t,{get:e[t],enumerable:!0})},Re=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xt(e))!kt.call(r,n)&&n!==t&&j(r,n,{get:()=>e[n],enumerable:!(s=Ut(e,n))||s.enumerable});return r};var U=(r,e,t)=>(t=r!=null?yt(wt(r)):{},Re(e||!r||!r.__esModule?j(t,"default",{value:r,enumerable:!0}):t,r)),Ft=r=>Re(j({},"__esModule",{value:!0}),r);var Es={};Pt(Es,{generateContext:()=>Se});module.exports=Ft(Es);var Mt=U(require("path"),1),Dt=require("os"),vt=require("fs");var ie=require("bun:sqlite");var g=require("path"),se=require("os"),D=require("fs");var Ae=require("url");var L=require("fs"),he=require("path");var $t=null;function Ht(r){return($t??process.stderr.write.bind(process.stderr))(r)}function Z(r){Ht(r)}var ee=(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))(ee||{}),te=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=x.logsDir();(0,L.existsSync)(e)||(0,L.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,he.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=x.settings();if((0,L.existsSync)(e)){let t=(0,L.readFileSync)(e,"utf-8"),n=(JSON.parse(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=ee[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}correlationId(e,t){return`obs-${e}-${t}`}sessionId(e){return`session-${e}`}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}
|
|
2
|
+
${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"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),d=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${s}-${n} ${o}:${i}:${a}.${d}`}log(e,t,s,n,o){if(e<this.getLevel())return;this.ensureLogFileInitialized();let i=this.formatTimestamp(new Date),a=ee[e].padEnd(5),d=t.padEnd(6),c="";n?.correlationId?c=`[${n.correlationId}] `:n?.sessionId&&(c=`[session-${n.sessionId}] `);let p="";if(o!=null)if(o instanceof Error)p=this.getLevel()===0?`
|
|
3
3
|
${o.message}
|
|
4
|
-
${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
5
|
-
`+JSON.stringify(o,null,2)}catch{
|
|
4
|
+
${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{p=`
|
|
5
|
+
`+JSON.stringify(o,null,2)}catch{p=" "+this.formatData(o)}else p=" "+this.formatData(o);let T="";if(n){let{sessionId:E,memorySessionId:f,correlationId:b,...m}=n;Object.keys(m).length>0&&(T=` {${Object.entries(m).map(([O,S])=>`${O}=${S}`).join(", ")}}`)}let l=`[${i}] [${a}] [${d}] ${c}${s}${T}${p}`;if(this.logFilePath)try{(0,L.appendFileSync)(this.logFilePath,l+`
|
|
6
6
|
`,"utf8")}catch(E){Z(`[LOGGER] Failed to write to log file: ${E instanceof Error?E.message:String(E)}
|
|
7
|
-
`)}else Z(
|
|
8
|
-
`)}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)}error(e,t,s,n){this.log(3,e,t,s,n)}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)}timing(e,t,s,n){this.info(e,`\u23F1 ${t}`,n,{duration:`${s}ms`})}happyPathError(e,t,s,n,o=""){let
|
|
9
|
-
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),c
|
|
7
|
+
`)}else Z(l+`
|
|
8
|
+
`)}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)}error(e,t,s,n){this.log(3,e,t,s,n)}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)}timing(e,t,s,n){this.info(e,`\u23F1 ${t}`,n,{duration:`${s}ms`})}happyPathError(e,t,s,n,o=""){let c=((new Error().stack||"").split(`
|
|
9
|
+
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),p=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",T={...s,location:p};return this.warn(e,`[HAPPY-PATH] ${t}`,T,n),o}},u=new te;var Jt={};function jt(){return typeof __dirname<"u"?__dirname:(0,g.dirname)((0,Ae.fileURLToPath)(Jt.url))}var Gt=jt();function Xt(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let r=(0,g.join)((0,se.homedir)(),".claude-mem"),e=(0,g.join)(r,"settings.json");try{if((0,D.existsSync)(e)){let t=JSON.parse((0,D.readFileSync)(e,"utf-8")),s=t.env??t;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return r}var R=Xt(),v=process.env.CLAUDE_CONFIG_DIR||(0,g.join)((0,se.homedir)(),".claude"),hs=(0,g.join)(v,"plugins","marketplaces","thedotmack"),Bt=(0,g.join)(R,"archives"),Wt=(0,g.join)(R,"logs"),Vt=(0,g.join)(R,"trash"),Yt=(0,g.join)(R,"backups"),qt=(0,g.join)(R,"modes"),As=(0,g.join)(R,"settings.json"),Ne=(0,g.join)(R,"claude-mem.db"),Kt=(0,g.join)(R,"vector-db"),Ce=(0,g.join)(R,"observer-sessions"),re=(0,g.basename)(Ce),Ns=(0,g.join)(v,"settings.json"),Cs=(0,g.join)(v,"commands"),Is=(0,g.join)(v,"CLAUDE.md");function Ie(r){(0,D.mkdirSync)(r,{recursive:!0})}function Le(){return(0,g.join)(Gt,"..")}var x={dataDir:()=>R,workerPid:()=>(0,g.join)(R,"worker.pid"),serverBetaPid:()=>(0,g.join)(R,".server-beta.pid"),serverBetaPort:()=>(0,g.join)(R,".server-beta.port"),serverBetaRuntime:()=>(0,g.join)(R,".server-beta.runtime.json"),settings:()=>(0,g.join)(R,"settings.json"),database:()=>(0,g.join)(R,"claude-mem.db"),chroma:()=>(0,g.join)(R,"chroma"),combinedCerts:()=>(0,g.join)(R,"combined_certs.pem"),transcriptsConfig:()=>(0,g.join)(R,"transcript-watch.json"),transcriptsState:()=>(0,g.join)(R,"transcript-watch-state.json"),corpora:()=>(0,g.join)(R,"corpora"),supervisorRegistry:()=>(0,g.join)(R,"supervisor.json"),envFile:()=>(0,g.join)(R,".env"),logsDir:()=>Wt,archives:()=>Bt,trash:()=>Vt,backups:()=>Yt,modes:()=>qt,vectorDb:()=>Kt,observerSessions:()=>Ce};var xe=require("crypto");var De=require("os"),ve=U(require("path"),1),ye=require("child_process");var X=require("fs"),G=U(require("path"),1);var w={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Me(r){let e=G.default.join(r,".git"),t;try{t=(0,X.statSync)(e)}catch(p){return p instanceof Error&&p.code!=="ENOENT"&&u.warn("GIT","Unexpected error checking .git",{error:p instanceof Error?p.message:String(p)}),w}if(!t.isFile())return w;let s;try{s=(0,X.readFileSync)(e,"utf-8").trim()}catch(p){return u.warn("GIT","Failed to read .git file",{error:p instanceof Error?p.message:String(p)}),w}let n=s.match(/^gitdir:\s*(.+)$/);if(!n)return w;let i=n[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!i)return w;let a=i[1],d=G.default.basename(r),c=G.default.basename(a);return{isWorktree:!0,worktreeName:d,parentRepoPath:a,parentProjectName:c}}function Ue(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,De.homedir)()):r}function Qt(r){try{return(0,ye.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function zt(r){if(!r||r.trim()==="")return u.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Ue(r),s=Qt(e)??e,n=ve.default.basename(s);if(n===""){if(process.platform==="win32"){let i=r.match(/^([A-Z]):\\/i);if(i){let d=`drive-${i[1].toUpperCase()}`;return u.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:d}),d}}return u.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return n}function ne(r){let e=zt(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Ue(r),s=Me(t);if(s.isWorktree&&s.parentProjectName){let n=`${s.parentProjectName}/${e}`;return{primary:n,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,n]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}function B(r,e,t){return(0,xe.createHash)("sha256").update([r||"",e||"",t||""].join("\0")).digest("hex").slice(0,16)}function oe(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[String(e)]}catch{return[r]}}var h="claude";function Zt(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function y(r){if(!r)return h;let e=Zt(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:h}function we(r){let e=["claude","codex","cursor"];return[...r].sort((t,s)=>{let n=e.indexOf(t),o=e.indexOf(s);return n!==-1||o!==-1?n===-1?1:o===-1?-1:n-o:t.localeCompare(s)})}function ke(r,e,t,s){let n=Date.now()-s;return r.prepare(`
|
|
10
|
+
SELECT
|
|
11
|
+
up.*,
|
|
12
|
+
s.memory_session_id,
|
|
13
|
+
s.project,
|
|
14
|
+
COALESCE(s.platform_source, '${h}') as platform_source
|
|
15
|
+
FROM user_prompts up
|
|
16
|
+
JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
|
|
17
|
+
WHERE up.content_session_id = ?
|
|
18
|
+
AND up.prompt_text = ?
|
|
19
|
+
AND up.created_at_epoch >= ?
|
|
20
|
+
ORDER BY up.created_at_epoch DESC
|
|
21
|
+
LIMIT 1
|
|
22
|
+
`).get(e,t,n)??void 0}function es(r,e){return{customTitle:r,platformSource:e?y(e):void 0}}var W=class{db;constructor(e=Ne){e instanceof ie.Database?this.db=e:(e!==":memory:"&&Ie(R),this.db=new ie.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA foreign_keys = ON"),this.db.run("PRAGMA journal_size_limit = 4194304")),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable(),this.ensureDiscoveryTokensColumn(),this.createPendingMessagesTable(),this.renameSessionIdColumns(),this.repairSessionIdColumnRename(),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()}dropWorkerPidColumn(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(32),s=this.db.query("PRAGMA table_info(pending_messages)").all().some(n=>n.name==="worker_pid");if(!(e&&!s)){if(s)try{this.db.run("DROP INDEX IF EXISTS idx_pending_messages_worker_pid"),this.db.run("ALTER TABLE pending_messages DROP COLUMN worker_pid"),u.debug("DB","Dropped worker_pid column and its index from pending_messages")}catch(n){u.warn("DB","Failed to drop worker_pid column from pending_messages",{},n instanceof Error?n:new Error(String(n)));return}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(32,new Date().toISOString())}}dropDeadPendingMessagesColumns(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(31),t=this.db.query("PRAGMA table_info(pending_messages)").all(),s=new Set(t.map(i=>i.name)),o=["retry_count","failed_at_epoch","completed_at_epoch"].filter(i=>s.has(i));if(!(e&&o.length===0)){if(o.length>0){this.db.run("BEGIN TRANSACTION");try{this.db.run("DELETE FROM pending_messages WHERE status NOT IN ('pending', 'processing')");for(let i of o)this.db.run(`ALTER TABLE pending_messages DROP COLUMN ${i}`),u.debug("DB",`Dropped dead column ${i} from pending_messages`);e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(31,new Date().toISOString()),this.db.run("COMMIT")}catch(i){this.db.run("ROLLBACK"),u.warn("DB","Failed to drop dead columns from pending_messages",{},i instanceof Error?i:new Error(String(i)));return}return}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(31,new Date().toISOString())}}initializeSchema(){this.db.run(`
|
|
10
23
|
CREATE TABLE IF NOT EXISTS schema_versions (
|
|
11
24
|
id INTEGER PRIMARY KEY,
|
|
12
25
|
version INTEGER UNIQUE NOT NULL,
|
|
@@ -190,7 +203,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
190
203
|
created_at_epoch INTEGER NOT NULL,
|
|
191
204
|
FOREIGN KEY (session_db_id) REFERENCES sdk_sessions(id) ON DELETE CASCADE
|
|
192
205
|
)
|
|
193
|
-
`),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()),u.debug("DB","pending_messages table created successfully")}renameSessionIdColumns(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(17))return;u.debug("DB","Checking session ID columns for semantic clarity rename");let t=0,s=(n,o,i)=>{let a=this.db.query(`PRAGMA table_info(${n})`).all(),d=a.some(
|
|
206
|
+
`),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()),u.debug("DB","pending_messages table created successfully")}renameSessionIdColumns(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(17))return;u.debug("DB","Checking session ID columns for semantic clarity rename");let t=0,s=(n,o,i)=>{let a=this.db.query(`PRAGMA table_info(${n})`).all(),d=a.some(p=>p.name===o);return a.some(p=>p.name===i)?!1:d?(this.db.run(`ALTER TABLE ${n} RENAME COLUMN ${o} TO ${i}`),u.debug("DB",`Renamed ${n}.${o} to ${i}`),!0):(u.warn("DB",`Column ${o} 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?u.debug("DB",`Successfully renamed ${t} session ID columns`):u.debug("DB","No session ID column renames needed (already up to date)")}repairSessionIdColumnRename(){this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(19)||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(19,new Date().toISOString())}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"),u.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;u.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 s=this.db.query("PRAGMA table_info(observations)").all().some(f=>f.name==="metadata"),n=s?`,
|
|
194
207
|
metadata TEXT`:"",o=s?", metadata":"",i=`
|
|
195
208
|
CREATE TABLE observations_new (
|
|
196
209
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -222,7 +235,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
222
235
|
CREATE INDEX idx_observations_project ON observations(project);
|
|
223
236
|
CREATE INDEX idx_observations_type ON observations(type);
|
|
224
237
|
CREATE INDEX idx_observations_created ON observations(created_at_epoch DESC);
|
|
225
|
-
`,
|
|
238
|
+
`,c=`
|
|
226
239
|
CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN
|
|
227
240
|
INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts)
|
|
228
241
|
VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts);
|
|
@@ -239,7 +252,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
239
252
|
INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts)
|
|
240
253
|
VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts);
|
|
241
254
|
END;
|
|
242
|
-
`;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
|
|
255
|
+
`;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 p=`
|
|
243
256
|
CREATE TABLE session_summaries_new (
|
|
244
257
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
245
258
|
memory_session_id TEXT NOT NULL,
|
|
@@ -264,7 +277,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
264
277
|
completed, next_steps, files_read, files_edited, notes,
|
|
265
278
|
prompt_number, discovery_tokens, created_at, created_at_epoch
|
|
266
279
|
FROM session_summaries
|
|
267
|
-
`,
|
|
280
|
+
`,l=`
|
|
268
281
|
CREATE INDEX idx_session_summaries_sdk_session ON session_summaries(memory_session_id);
|
|
269
282
|
CREATE INDEX idx_session_summaries_project ON session_summaries(project);
|
|
270
283
|
CREATE INDEX idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
|
|
@@ -285,9 +298,9 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
285
298
|
INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
|
|
286
299
|
VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes);
|
|
287
300
|
END;
|
|
288
|
-
`;try{this.recreateObservationsWithCascade(i,a,d,
|
|
301
|
+
`;try{this.recreateObservationsWithCascade(i,a,d,c),this.recreateSessionSummariesWithCascade(p,T,l,E),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"),u.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)"),u.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(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(23))return;this.db.query("PRAGMA table_info(sdk_sessions)").all().some(n=>n.name==="custom_title")||(this.db.run("ALTER TABLE sdk_sessions ADD COLUMN custom_title TEXT"),u.debug("DB","Added custom_title column to sdk_sessions table")),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(i=>i.name==="platform_source"),n=this.db.query("PRAGMA index_list(sdk_sessions)").all().some(i=>i.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 '${h}'`),u.debug("DB","Added platform_source column to sdk_sessions table")),this.db.run(`
|
|
289
302
|
UPDATE sdk_sessions
|
|
290
|
-
SET platform_source = '${
|
|
303
|
+
SET platform_source = '${h}'
|
|
291
304
|
WHERE platform_source IS NULL OR platform_source = ''
|
|
292
305
|
`),n||this.db.run("CREATE INDEX IF NOT EXISTS idx_sdk_sessions_platform_source ON sdk_sessions(platform_source)"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(24,new Date().toISOString()))}addObservationModelColumns(){let e=this.db.query("PRAGMA table_info(observations)").all(),t=e.some(n=>n.name==="generated_by_model"),s=e.some(n=>n.name==="relevance_count");t&&s||(t||this.db.run("ALTER TABLE observations ADD COLUMN generated_by_model TEXT"),s||this.db.run("ALTER TABLE observations ADD COLUMN relevance_count INTEGER DEFAULT 0"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(26,new Date().toISOString()))}ensureMergedIntoProjectColumns(){this.db.query("PRAGMA table_info(observations)").all().some(s=>s.name==="merged_into_project")||this.db.run("ALTER TABLE observations ADD COLUMN merged_into_project TEXT"),this.db.run("CREATE INDEX IF NOT EXISTS idx_observations_merged_into ON observations(merged_into_project)"),this.db.query("PRAGMA table_info(session_summaries)").all().some(s=>s.name==="merged_into_project")||this.db.run("ALTER TABLE session_summaries ADD COLUMN merged_into_project TEXT"),this.db.run("CREATE INDEX IF NOT EXISTS idx_summaries_merged_into ON session_summaries(merged_into_project)")}addObservationSubagentColumns(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(27),t=this.db.query("PRAGMA table_info(observations)").all(),s=t.some(i=>i.name==="agent_type"),n=t.some(i=>i.name==="agent_id");s||this.db.run("ALTER TABLE observations ADD COLUMN agent_type TEXT"),n||this.db.run("ALTER TABLE observations ADD COLUMN agent_id TEXT"),this.db.run("CREATE INDEX IF NOT EXISTS idx_observations_agent_type ON observations(agent_type)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_observations_agent_id ON observations(agent_id)");let o=this.db.query("PRAGMA table_info(pending_messages)").all();if(o.length>0){let i=o.some(d=>d.name==="agent_type"),a=o.some(d=>d.name==="agent_id");i||this.db.run("ALTER TABLE pending_messages ADD COLUMN agent_type TEXT"),a||this.db.run("ALTER TABLE pending_messages ADD COLUMN agent_id TEXT")}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(27,new Date().toISOString())}ensurePendingMessagesToolUseIdColumn(){if(this.db.query("SELECT name FROM sqlite_master WHERE type='table' AND name='pending_messages'").all().length===0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(28,new Date().toISOString());return}this.db.query("PRAGMA table_info(pending_messages)").all().some(n=>n.name==="tool_use_id")||this.db.run("ALTER TABLE pending_messages ADD COLUMN tool_use_id TEXT"),this.db.run("BEGIN TRANSACTION");try{this.db.run(`
|
|
293
306
|
DELETE FROM pending_messages
|
|
@@ -367,7 +380,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
367
380
|
o.subtitle,
|
|
368
381
|
o.text,
|
|
369
382
|
o.project,
|
|
370
|
-
COALESCE(s.platform_source, '${
|
|
383
|
+
COALESCE(s.platform_source, '${h}') as platform_source,
|
|
371
384
|
o.prompt_number,
|
|
372
385
|
o.created_at,
|
|
373
386
|
o.created_at_epoch
|
|
@@ -387,7 +400,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
387
400
|
ss.files_edited,
|
|
388
401
|
ss.notes,
|
|
389
402
|
ss.project,
|
|
390
|
-
COALESCE(s.platform_source, '${
|
|
403
|
+
COALESCE(s.platform_source, '${h}') as platform_source,
|
|
391
404
|
ss.prompt_number,
|
|
392
405
|
ss.created_at,
|
|
393
406
|
ss.created_at_epoch
|
|
@@ -400,7 +413,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
400
413
|
up.id,
|
|
401
414
|
up.content_session_id,
|
|
402
415
|
s.project,
|
|
403
|
-
COALESCE(s.platform_source, '${
|
|
416
|
+
COALESCE(s.platform_source, '${h}') as platform_source,
|
|
404
417
|
up.prompt_number,
|
|
405
418
|
up.prompt_text,
|
|
406
419
|
up.created_at,
|
|
@@ -414,28 +427,28 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
414
427
|
FROM sdk_sessions
|
|
415
428
|
WHERE project IS NOT NULL AND project != ''
|
|
416
429
|
AND project != ?
|
|
417
|
-
`,n=[re];return t&&(s+=" AND COALESCE(platform_source, ?) = ?",n.push(
|
|
430
|
+
`,n=[re];return t&&(s+=" AND COALESCE(platform_source, ?) = ?",n.push(h,t)),s+=" ORDER BY project ASC",this.db.prepare(s).all(...n).map(i=>i.project)}getProjectCatalog(){let e=this.db.prepare(`
|
|
418
431
|
SELECT
|
|
419
|
-
COALESCE(platform_source, '${
|
|
432
|
+
COALESCE(platform_source, '${h}') as platform_source,
|
|
420
433
|
project,
|
|
421
434
|
MAX(started_at_epoch) as latest_epoch
|
|
422
435
|
FROM sdk_sessions
|
|
423
436
|
WHERE project IS NOT NULL AND project != ''
|
|
424
437
|
AND project != ?
|
|
425
|
-
GROUP BY COALESCE(platform_source, '${
|
|
438
|
+
GROUP BY COALESCE(platform_source, '${h}'), project
|
|
426
439
|
ORDER BY latest_epoch DESC
|
|
427
440
|
`).all(re),t=[],s=new Set,n={};for(let i of e){let a=y(i.platform_source);n[a]||(n[a]=[]),n[a].includes(i.project)||n[a].push(i.project),s.has(i.project)||(s.add(i.project),t.push(i.project))}let o=we(Object.keys(n));return{projects:t,sources:o,projectsBySource:Object.fromEntries(o.map(i=>[i,n[i]||[]]))}}getLatestUserPrompt(e){return this.db.prepare(`
|
|
428
441
|
SELECT
|
|
429
442
|
up.*,
|
|
430
443
|
s.memory_session_id,
|
|
431
444
|
s.project,
|
|
432
|
-
COALESCE(s.platform_source, '${
|
|
445
|
+
COALESCE(s.platform_source, '${h}') as platform_source
|
|
433
446
|
FROM user_prompts up
|
|
434
447
|
JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
|
|
435
448
|
WHERE up.content_session_id = ?
|
|
436
449
|
ORDER BY up.created_at_epoch DESC
|
|
437
450
|
LIMIT 1
|
|
438
|
-
`).get(e)}getRecentSessionsWithStatus(e,t=3){return this.db.prepare(`
|
|
451
|
+
`).get(e)}findRecentDuplicateUserPrompt(e,t,s){return ke(this.db,e,t,s)}getRecentSessionsWithStatus(e,t=3){return this.db.prepare(`
|
|
439
452
|
SELECT * FROM (
|
|
440
453
|
SELECT
|
|
441
454
|
s.memory_session_id,
|
|
@@ -461,13 +474,13 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
461
474
|
SELECT *
|
|
462
475
|
FROM observations
|
|
463
476
|
WHERE id = ?
|
|
464
|
-
`).get(e)||null}getObservationsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o,type:i,concepts:a,files:d}=t,
|
|
477
|
+
`).get(e)||null}getObservationsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o,type:i,concepts:a,files:d}=t,c=s==="relevance",p=c?"":`ORDER BY created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,T=n?`LIMIT ${n}`:"",l=e.map(()=>"?").join(","),E=[...e],f=[];if(o&&(f.push("project = ?"),E.push(o)),i)if(Array.isArray(i)){let S=i.map(()=>"?").join(",");f.push(`type IN (${S})`),E.push(...i)}else f.push("type = ?"),E.push(i);if(a){let S=Array.isArray(a)?a:[a],A=S.map(()=>"EXISTS (SELECT 1 FROM json_each(concepts) WHERE value = ?)");E.push(...S),f.push(`(${A.join(" OR ")})`)}if(d){let S=Array.isArray(d)?d:[d],A=S.map(()=>"(EXISTS (SELECT 1 FROM json_each(files_read) WHERE value LIKE ?) OR EXISTS (SELECT 1 FROM json_each(files_modified) WHERE value LIKE ?))");S.forEach(M=>{E.push(`%${M}%`,`%${M}%`)}),f.push(`(${A.join(" OR ")})`)}let b=f.length>0?`WHERE id IN (${l}) AND ${f.join(" AND ")}`:`WHERE id IN (${l})`,N=this.db.prepare(`
|
|
465
478
|
SELECT *
|
|
466
479
|
FROM observations
|
|
467
480
|
${b}
|
|
468
|
-
${
|
|
481
|
+
${p}
|
|
469
482
|
${T}
|
|
470
|
-
`).all(...E);if(!
|
|
483
|
+
`).all(...E);if(!c)return N;let O=new Map(N.map(S=>[S.id,S]));return e.map(S=>O.get(S)).filter(S=>!!S)}getSummaryForSession(e){return this.db.prepare(`
|
|
471
484
|
SELECT
|
|
472
485
|
request, investigated, learned, completed, next_steps,
|
|
473
486
|
files_read, files_edited, notes, prompt_number, created_at,
|
|
@@ -482,14 +495,14 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
482
495
|
WHERE memory_session_id = ?
|
|
483
496
|
`).all(e),n=new Set,o=new Set;for(let i of s)oe(i.files_read).forEach(a=>n.add(a)),oe(i.files_modified).forEach(a=>o.add(a));return{filesRead:Array.from(n),filesModified:Array.from(o)}}getSessionById(e){return this.db.prepare(`
|
|
484
497
|
SELECT id, content_session_id, memory_session_id, project,
|
|
485
|
-
COALESCE(platform_source, '${
|
|
498
|
+
COALESCE(platform_source, '${h}') as platform_source,
|
|
486
499
|
user_prompt, custom_title, status
|
|
487
500
|
FROM sdk_sessions
|
|
488
501
|
WHERE id = ?
|
|
489
502
|
LIMIT 1
|
|
490
503
|
`).get(e)||null}getSdkSessionsBySessionIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.db.prepare(`
|
|
491
504
|
SELECT id, content_session_id, memory_session_id, project,
|
|
492
|
-
COALESCE(platform_source, '${
|
|
505
|
+
COALESCE(platform_source, '${h}') as platform_source,
|
|
493
506
|
user_prompt, custom_title,
|
|
494
507
|
started_at, started_at_epoch, completed_at, completed_at_epoch, status
|
|
495
508
|
FROM sdk_sessions
|
|
@@ -497,23 +510,23 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
497
510
|
ORDER BY started_at_epoch DESC
|
|
498
511
|
`).all(...e)}getPromptNumberFromUserPrompts(e){return this.db.prepare(`
|
|
499
512
|
SELECT COUNT(*) as count FROM user_prompts WHERE content_session_id = ?
|
|
500
|
-
`).get(e).count}createSDKSession(e,t,s,n,o){let i=new Date,a=i.getTime(),d=
|
|
513
|
+
`).get(e).count}createSDKSession(e,t,s,n,o){let i=new Date,a=i.getTime(),d=es(n,o),c=d.platformSource??h,p=this.db.prepare(`
|
|
501
514
|
SELECT id, platform_source FROM sdk_sessions WHERE content_session_id = ?
|
|
502
|
-
`).get(e);if(
|
|
515
|
+
`).get(e);if(p){if(t&&this.db.prepare(`
|
|
503
516
|
UPDATE sdk_sessions SET project = ?
|
|
504
517
|
WHERE content_session_id = ? AND (project IS NULL OR project = '')
|
|
505
518
|
`).run(t,e),d.customTitle&&this.db.prepare(`
|
|
506
519
|
UPDATE sdk_sessions SET custom_title = ?
|
|
507
520
|
WHERE content_session_id = ? AND custom_title IS NULL
|
|
508
|
-
`).run(d.customTitle,e),d.platformSource){let p
|
|
521
|
+
`).run(d.customTitle,e),d.platformSource){let l=p.platform_source?.trim()?y(p.platform_source):void 0;if(!l)this.db.prepare(`
|
|
509
522
|
UPDATE sdk_sessions SET platform_source = ?
|
|
510
523
|
WHERE content_session_id = ?
|
|
511
524
|
AND COALESCE(platform_source, '') = ''
|
|
512
|
-
`).run(d.platformSource,e);else if(
|
|
525
|
+
`).run(d.platformSource,e);else if(l!==d.platformSource)throw new Error(`Platform source conflict for session ${e}: existing=${l}, received=${d.platformSource}`)}return p.id}return this.db.prepare(`
|
|
513
526
|
INSERT INTO sdk_sessions
|
|
514
527
|
(content_session_id, memory_session_id, project, platform_source, user_prompt, custom_title, started_at, started_at_epoch, status)
|
|
515
528
|
VALUES (?, NULL, ?, ?, ?, ?, ?, ?, 'active')
|
|
516
|
-
`).run(e,t,
|
|
529
|
+
`).run(e,t,c,s,d.customTitle||null,i.toISOString(),a),this.db.prepare("SELECT id FROM sdk_sessions WHERE content_session_id = ?").get(e).id}saveUserPrompt(e,t,s){let n=new Date,o=n.getTime();return this.db.prepare(`
|
|
517
530
|
INSERT INTO user_prompts
|
|
518
531
|
(content_session_id, prompt_number, prompt_text, created_at, created_at_epoch)
|
|
519
532
|
VALUES (?, ?, ?, ?, ?)
|
|
@@ -522,7 +535,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
522
535
|
FROM user_prompts
|
|
523
536
|
WHERE content_session_id = ? AND prompt_number = ?
|
|
524
537
|
LIMIT 1
|
|
525
|
-
`).get(e,t)?.prompt_text??null}storeObservation(e,t,s,n,o=0,i,a){let d=i??Date.now(),
|
|
538
|
+
`).get(e,t)?.prompt_text??null}storeObservation(e,t,s,n,o=0,i,a){let d=i??Date.now(),c=new Date(d).toISOString(),p=B(e,s.title,s.narrative),l=this.db.prepare(`
|
|
526
539
|
INSERT INTO observations
|
|
527
540
|
(memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
|
|
528
541
|
files_read, files_modified, prompt_number, discovery_tokens, agent_type, agent_id, content_hash, created_at, created_at_epoch,
|
|
@@ -530,12 +543,12 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
530
543
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
531
544
|
ON CONFLICT(memory_session_id, content_hash) DO NOTHING
|
|
532
545
|
RETURNING id, created_at_epoch
|
|
533
|
-
`).get(e,t,s.type,s.title,s.subtitle,JSON.stringify(s.facts),s.narrative,JSON.stringify(s.concepts),JSON.stringify(s.files_read),JSON.stringify(s.files_modified),n||null,o,s.agent_type??null,s.agent_id??null,c,
|
|
546
|
+
`).get(e,t,s.type,s.title,s.subtitle,JSON.stringify(s.facts),s.narrative,JSON.stringify(s.concepts),JSON.stringify(s.files_read),JSON.stringify(s.files_modified),n||null,o,s.agent_type??null,s.agent_id??null,p,c,d,a||null,s.metadata??null);if(l)return{id:l.id,createdAtEpoch:l.created_at_epoch};let E=this.db.prepare("SELECT id, created_at_epoch FROM observations WHERE memory_session_id = ? AND content_hash = ?").get(e,p);if(!E)throw new Error(`storeObservation: ON CONFLICT without existing row for content_hash=${p}`);return{id:E.id,createdAtEpoch:E.created_at_epoch}}storeSummary(e,t,s,n,o=0,i){let a=i??Date.now(),d=new Date(a).toISOString(),p=this.db.prepare(`
|
|
534
547
|
INSERT INTO session_summaries
|
|
535
548
|
(memory_session_id, project, request, investigated, learned, completed,
|
|
536
549
|
next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
|
|
537
550
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
538
|
-
`).run(e,t,s.request,s.investigated,s.learned,s.completed,s.next_steps,s.notes,n||null,o,d,a);return{id:Number(
|
|
551
|
+
`).run(e,t,s.request,s.investigated,s.learned,s.completed,s.next_steps,s.notes,n||null,o,d,a);return{id:Number(p.lastInsertRowid),createdAtEpoch:a}}storeObservations(e,t,s,n,o,i=0,a,d){let c=a??Date.now(),p=new Date(c).toISOString();return this.db.transaction(()=>{let l=[],E=this.db.prepare(`
|
|
539
552
|
INSERT INTO observations
|
|
540
553
|
(memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
|
|
541
554
|
files_read, files_modified, prompt_number, discovery_tokens, agent_type, agent_id, content_hash, created_at, created_at_epoch,
|
|
@@ -543,12 +556,12 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
543
556
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
544
557
|
ON CONFLICT(memory_session_id, content_hash) DO NOTHING
|
|
545
558
|
RETURNING id
|
|
546
|
-
`),f=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let
|
|
559
|
+
`),f=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let m of s){let N=B(e,m.title,m.narrative),O=E.get(e,t,m.type,m.title,m.subtitle,JSON.stringify(m.facts),m.narrative,JSON.stringify(m.concepts),JSON.stringify(m.files_read),JSON.stringify(m.files_modified),o||null,i,m.agent_type??null,m.agent_id??null,N,p,c,d||null);if(O){l.push(O.id);continue}let S=f.get(e,N);if(!S)throw new Error(`storeObservations: ON CONFLICT without existing row for content_hash=${N}`);l.push(S.id)}let b=null;if(n){let N=this.db.prepare(`
|
|
547
560
|
INSERT INTO session_summaries
|
|
548
561
|
(memory_session_id, project, request, investigated, learned, completed,
|
|
549
562
|
next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
|
|
550
563
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
551
|
-
`).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,o||null,i,c
|
|
564
|
+
`).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,o||null,i,p,c);b=Number(N.lastInsertRowid)}return{observationIds:l,summaryId:b,createdAtEpoch:c}})()}storeObservationsAndMarkComplete(e,t,s,n,o,i,a,d=0,c,p){let T=c??Date.now(),l=new Date(T).toISOString();return this.db.transaction(()=>{let f=[],b=this.db.prepare(`
|
|
552
565
|
INSERT INTO observations
|
|
553
566
|
(memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
|
|
554
567
|
files_read, files_modified, prompt_number, discovery_tokens, agent_type, agent_id, content_hash, created_at, created_at_epoch,
|
|
@@ -556,54 +569,54 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
556
569
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
557
570
|
ON CONFLICT(memory_session_id, content_hash) DO NOTHING
|
|
558
571
|
RETURNING id
|
|
559
|
-
`),
|
|
572
|
+
`),m=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let A of s){let M=B(e,A.title,A.narrative),be=b.get(e,t,A.type,A.title,A.subtitle,JSON.stringify(A.facts),A.narrative,JSON.stringify(A.concepts),JSON.stringify(A.files_read),JSON.stringify(A.files_modified),a||null,d,A.agent_type??null,A.agent_id??null,M,l,T,p||null);if(be){f.push(be.id);continue}let Oe=m.get(e,M);if(!Oe)throw new Error(`storeObservationsAndMarkComplete: ON CONFLICT without existing row for content_hash=${M}`);f.push(Oe.id)}let N;if(n){let M=this.db.prepare(`
|
|
560
573
|
INSERT INTO session_summaries
|
|
561
574
|
(memory_session_id, project, request, investigated, learned, completed,
|
|
562
575
|
next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
|
|
563
576
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
564
|
-
`).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,a||null,d,
|
|
577
|
+
`).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,a||null,d,l,T);N=Number(M.lastInsertRowid)}if(this.db.prepare(`
|
|
565
578
|
DELETE FROM pending_messages
|
|
566
579
|
WHERE id = ? AND status = 'processing'
|
|
567
|
-
`).run(o).changes!==1)throw new Error(`storeObservationsAndMarkComplete: failed to complete pending message ${o}`);return{observationIds:f,summaryId:
|
|
580
|
+
`).run(o).changes!==1)throw new Error(`storeObservationsAndMarkComplete: failed to complete pending message ${o}`);return{observationIds:f,summaryId:N,createdAtEpoch:T}})()}getSessionSummariesByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o}=t,i=s==="relevance",a=i?"":`ORDER BY created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,d=n?`LIMIT ${n}`:"",c=e.map(()=>"?").join(","),p=[...e],T=o?`WHERE id IN (${c}) AND project = ?`:`WHERE id IN (${c})`;o&&p.push(o);let E=this.db.prepare(`
|
|
568
581
|
SELECT * FROM session_summaries
|
|
569
582
|
${T}
|
|
570
583
|
${a}
|
|
571
584
|
${d}
|
|
572
|
-
`).all(...
|
|
585
|
+
`).all(...p);if(!i)return E;let f=new Map(E.map(b=>[b.id,b]));return e.map(b=>f.get(b)).filter(b=>!!b)}getUserPromptsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o}=t,i=s==="relevance",a=i?"":`ORDER BY up.created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,d=n?`LIMIT ${n}`:"",c=e.map(()=>"?").join(","),p=[...e],T=o?"AND s.project = ?":"";o&&p.push(o);let E=this.db.prepare(`
|
|
573
586
|
SELECT
|
|
574
587
|
up.*,
|
|
575
588
|
s.project,
|
|
576
589
|
s.memory_session_id
|
|
577
590
|
FROM user_prompts up
|
|
578
591
|
JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
|
|
579
|
-
WHERE up.id IN (${
|
|
592
|
+
WHERE up.id IN (${c}) ${T}
|
|
580
593
|
${a}
|
|
581
594
|
${d}
|
|
582
|
-
`).all(...
|
|
595
|
+
`).all(...p);if(!i)return E;let f=new Map(E.map(b=>[b.id,b]));return e.map(b=>f.get(b)).filter(b=>!!b)}getTimelineAroundTimestamp(e,t=10,s=10,n){return this.getTimelineAroundObservation(null,e,t,s,n)}getTimelineAroundObservation(e,t,s=10,n=10,o){let i=o?"AND project = ?":"",a=o?[o]:[],d,c;if(e!==null){let m=`
|
|
583
596
|
SELECT id, created_at_epoch
|
|
584
597
|
FROM observations
|
|
585
598
|
WHERE id <= ? ${i}
|
|
586
599
|
ORDER BY id DESC
|
|
587
600
|
LIMIT ?
|
|
588
|
-
`,
|
|
601
|
+
`,N=`
|
|
589
602
|
SELECT id, created_at_epoch
|
|
590
603
|
FROM observations
|
|
591
604
|
WHERE id >= ? ${i}
|
|
592
605
|
ORDER BY id ASC
|
|
593
606
|
LIMIT ?
|
|
594
|
-
`;try{let
|
|
607
|
+
`;try{let O=this.db.prepare(m).all(e,...a,s+1),S=this.db.prepare(N).all(e,...a,n+1);if(O.length===0&&S.length===0)return{observations:[],sessions:[],prompts:[]};d=O.length>0?O[O.length-1].created_at_epoch:t,c=S.length>0?S[S.length-1].created_at_epoch:t}catch(O){return O instanceof Error?u.error("DB","Error getting boundary observations",{project:o},O):u.error("DB","Error getting boundary observations with non-Error",{},new Error(String(O))),{observations:[],sessions:[],prompts:[]}}}else{let m=`
|
|
595
608
|
SELECT created_at_epoch
|
|
596
609
|
FROM observations
|
|
597
610
|
WHERE created_at_epoch <= ? ${i}
|
|
598
611
|
ORDER BY created_at_epoch DESC
|
|
599
612
|
LIMIT ?
|
|
600
|
-
`,
|
|
613
|
+
`,N=`
|
|
601
614
|
SELECT created_at_epoch
|
|
602
615
|
FROM observations
|
|
603
616
|
WHERE created_at_epoch >= ? ${i}
|
|
604
617
|
ORDER BY created_at_epoch ASC
|
|
605
618
|
LIMIT ?
|
|
606
|
-
`;try{let
|
|
619
|
+
`;try{let O=this.db.prepare(m).all(t,...a,s),S=this.db.prepare(N).all(t,...a,n+1);if(O.length===0&&S.length===0)return{observations:[],sessions:[],prompts:[]};d=O.length>0?O[O.length-1].created_at_epoch:t,c=S.length>0?S[S.length-1].created_at_epoch:t}catch(O){return O instanceof Error?u.error("DB","Error getting boundary timestamps",{project:o},O):u.error("DB","Error getting boundary timestamps with non-Error",{},new Error(String(O))),{observations:[],sessions:[],prompts:[]}}}let p=`
|
|
607
620
|
SELECT *
|
|
608
621
|
FROM observations
|
|
609
622
|
WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${i}
|
|
@@ -613,13 +626,13 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
613
626
|
FROM session_summaries
|
|
614
627
|
WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${i}
|
|
615
628
|
ORDER BY created_at_epoch ASC
|
|
616
|
-
`,
|
|
629
|
+
`,l=`
|
|
617
630
|
SELECT up.*, s.project, s.memory_session_id
|
|
618
631
|
FROM user_prompts up
|
|
619
632
|
JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
|
|
620
633
|
WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${i.replace("project","s.project")}
|
|
621
634
|
ORDER BY up.created_at_epoch ASC
|
|
622
|
-
`,E=this.db.prepare(
|
|
635
|
+
`,E=this.db.prepare(p).all(d,c,...a),f=this.db.prepare(T).all(d,c,...a),b=this.db.prepare(l).all(d,c,...a);return{observations:E,sessions:f.map(m=>({id:m.id,memory_session_id:m.memory_session_id,project:m.project,request:m.request,completed:m.completed,next_steps:m.next_steps,created_at:m.created_at,created_at_epoch:m.created_at_epoch})),prompts:b.map(m=>({id:m.id,content_session_id:m.content_session_id,prompt_number:m.prompt_number,prompt_text:m.prompt_text,project:m.project,created_at:m.created_at,created_at_epoch:m.created_at_epoch}))}}getPromptById(e){return this.db.prepare(`
|
|
623
636
|
SELECT
|
|
624
637
|
p.id,
|
|
625
638
|
p.content_session_id,
|
|
@@ -663,7 +676,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
663
676
|
`).get(e)||null}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 o=new Date;return this.db.prepare(`
|
|
664
677
|
INSERT INTO sdk_sessions (memory_session_id, content_session_id, project, platform_source, started_at, started_at_epoch, status)
|
|
665
678
|
VALUES (?, ?, ?, ?, ?, ?, 'active')
|
|
666
|
-
`).run(t,s,e,
|
|
679
|
+
`).run(t,s,e,h,o.toISOString(),o.getTime()),u.info("SESSION","Created manual session",{memorySessionId:t,project:e}),t}close(){this.db.close()}importSdkSession(e){let t=this.db.prepare("SELECT id FROM sdk_sessions WHERE content_session_id = ?").get(e.content_session_id);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(`
|
|
667
680
|
INSERT INTO sdk_sessions (
|
|
668
681
|
content_session_id, memory_session_id, project, platform_source, user_prompt,
|
|
669
682
|
started_at, started_at_epoch, completed_at, completed_at_epoch, status
|
|
@@ -692,7 +705,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
692
705
|
content_session_id, prompt_number, prompt_text,
|
|
693
706
|
created_at, created_at_epoch
|
|
694
707
|
) VALUES (?, ?, ?, ?, ?)
|
|
695
|
-
`).run(e.content_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var I=require("fs"),k=require("path"),ae=require("os"),V=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,k.join)((0,ae.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,k.join)((0,ae.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static getBool(e){let t=this.get(e);return t==="true"||t===!0}static applyEnvOverrides(e){let t={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(t[s]=process.env[s]);return t}static loadFromFile(e){try{if(!(0,I.existsSync)(e)){let i=this.getAllDefaults();try{let a=(0,k.dirname)(e);(0,I.existsSync)(a)||(0,I.mkdirSync)(a,{recursive:!0}),(0,I.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,a instanceof Error?a.message:String(a))}return this.applyEnvOverrides(i)}let t=(0,I.readFileSync)(e,"utf-8"),s=JSON.parse(t),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{(0,I.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(i){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,i instanceof Error?i.message:String(i))}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(o[i]=n[i]);return this.applyEnvOverrides(o)}catch(t){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,t instanceof Error?t.message:String(t)),this.applyEnvOverrides(this.getAllDefaults())}}};var F=require("fs"),q=require("path");var C=class r{static instance=null;activeMode=null;modesDir;constructor(){let e=Le(),t=[(0,q.join)(e,"modes"),(0,q.join)(e,"..","plugin","modes")],s=t.find(n=>(0,F.existsSync)(n));this.modesDir=s||t[0]}static getInstance(){return r.instance||(r.instance=new r),r.instance}parseInheritance(e){let t=e.split("--");if(t.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(t.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:t[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,t){let s={...e};for(let n in t){let o=t[n],i=e[n];this.isPlainObject(o)&&this.isPlainObject(i)?s[n]=this.deepMerge(i,o):s[n]=o}return s}loadModeFile(e){let t=(0,q.join)(this.modesDir,`${e}.json`);if(!(0,F.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let s=(0,F.readFileSync)(t,"utf-8");return JSON.parse(s)}loadMode(e){let t=this.parseInheritance(e);if(!t.hasParent)try{let d=this.loadModeFile(e);return this.activeMode=d,u.debug("SYSTEM",`Loaded mode: ${d.name} (${e})`,void 0,{types:d.observation_types.map(m=>m.id),concepts:d.observation_concepts.map(m=>m.id)}),d}catch(d){if(d instanceof Error?u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:d.message}):u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(d)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:s,overrideId:n}=t,o;try{o=this.loadMode(s)}catch(d){d instanceof Error?u.warn("WORKER",`Parent mode '${s}' not found for ${e}, falling back to 'code'`,{message:d.message}):u.warn("WORKER",`Parent mode '${s}' not found for ${e}, falling back to 'code'`,{error:String(d)}),o=this.loadMode("code")}let i;try{i=this.loadModeFile(n),u.debug("SYSTEM",`Loaded override file: ${n} for parent ${s}`)}catch(d){return d instanceof Error?u.warn("WORKER",`Override file '${n}' not found, using parent mode '${s}' only`,{message:d.message}):u.warn("WORKER",`Override file '${n}' not found, using parent mode '${s}' only`,{error:String(d)}),this.activeMode=o,o}if(!i)return u.warn("SYSTEM",`Invalid override file: ${n}, using parent mode '${s}' only`),this.activeMode=o,o;let a=this.deepMerge(o,i);return this.activeMode=a,u.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${s} + ${n})`,void 0,{parent:s,override:n,types:a.observation_types.map(d=>d.id),concepts:a.observation_concepts.map(d=>d.id)}),a}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getObservationConcepts(){return this.getActiveMode().observation_concepts}getTypeIcon(e){return this.getObservationTypes().find(s=>s.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(s=>s.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(t=>t.id===e)}getTypeLabel(e){return this.getObservationTypes().find(s=>s.id===e)?.label||e}};function de(){let r=x.settings(),e=V.loadFromFile(r),t=C.getInstance().getActiveMode(),s=new Set(t.observation_types.map(o=>o.id)),n=new Set(t.observation_concepts.map(o=>o.id));return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:s,observationConcepts:n,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}var _={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},ke=4,_e=1;function ue(r){let e=(r.title?.length||0)+(r.subtitle?.length||0)+(r.narrative?.length||0)+JSON.stringify(r.facts||[]).length;return Math.ceil(e/ke)}function ce(r){let e=r.length,t=r.reduce((i,a)=>i+ue(a),0),s=r.reduce((i,a)=>i+(a.discovery_tokens||0),0),n=s-t,o=s>0?Math.round(n/s*100):0;return{totalObservations:e,totalReadTokens:t,totalDiscoveryTokens:s,savings:n,savingsPercent:o}}function es(r){return C.getInstance().getWorkEmoji(r)}function $(r,e){let t=ue(r),s=r.discovery_tokens||0,n=es(r.type),o=s>0?`${n} ${s.toLocaleString()}`:"-";return{readTokens:t,discoveryTokens:s,discoveryDisplay:o,workEmoji:n}}function Y(r){return r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent}var $e=U(require("path"),1),K=require("fs");var ts=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],rr=new RegExp(`<(${ts.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),Fe=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var ss=["task-notification"],nr=new RegExp(`^\\s*<(${ss.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),or=256*1024;function me(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(",");return r.db.prepare(`
|
|
708
|
+
`).run(e.content_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var I=require("fs"),k=require("path"),ae=require("os"),V=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,k.join)((0,ae.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,k.join)((0,ae.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static getBool(e){let t=this.get(e);return t==="true"||t===!0}static applyEnvOverrides(e){let t={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(t[s]=process.env[s]);return t}static loadFromFile(e){try{if(!(0,I.existsSync)(e)){let i=this.getAllDefaults();try{let a=(0,k.dirname)(e);(0,I.existsSync)(a)||(0,I.mkdirSync)(a,{recursive:!0}),(0,I.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,a instanceof Error?a.message:String(a))}return this.applyEnvOverrides(i)}let t=(0,I.readFileSync)(e,"utf-8"),s=JSON.parse(t.replace(/^\uFEFF/,"")),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{(0,I.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(i){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,i instanceof Error?i.message:String(i))}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(o[i]=n[i]);return this.applyEnvOverrides(o)}catch(t){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,t instanceof Error?t.message:String(t)),this.applyEnvOverrides(this.getAllDefaults())}}};var P=require("fs"),Y=require("path");var C=class r{static instance=null;activeMode=null;modesDir;constructor(){let e=Le(),t=[...process.env.CLAUDE_MEM_MODES_DIR?[process.env.CLAUDE_MEM_MODES_DIR]:[],(0,Y.join)(e,"modes"),(0,Y.join)(e,"..","plugin","modes")],s=t.find(n=>(0,P.existsSync)(n));this.modesDir=s||t[0]}static getInstance(){return r.instance||(r.instance=new r),r.instance}parseInheritance(e){let t=e.split("--");if(t.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(t.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:t[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,t){let s={...e};for(let n in t){let o=t[n],i=e[n];this.isPlainObject(o)&&this.isPlainObject(i)?s[n]=this.deepMerge(i,o):s[n]=o}return s}loadModeFile(e){let t=(0,Y.join)(this.modesDir,`${e}.json`);if(!(0,P.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let s=(0,P.readFileSync)(t,"utf-8");return JSON.parse(s)}loadMode(e){let t=this.parseInheritance(e);if(!t.hasParent)try{let d=this.loadModeFile(e);return this.activeMode=d,u.debug("SYSTEM",`Loaded mode: ${d.name} (${e})`,void 0,{types:d.observation_types.map(c=>c.id),concepts:d.observation_concepts.map(c=>c.id)}),d}catch(d){if(d instanceof Error?u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:d.message}):u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(d)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:s,overrideId:n}=t,o;try{o=this.loadMode(s)}catch(d){d instanceof Error?u.warn("WORKER",`Parent mode '${s}' not found for ${e}, falling back to 'code'`,{message:d.message}):u.warn("WORKER",`Parent mode '${s}' not found for ${e}, falling back to 'code'`,{error:String(d)}),o=this.loadMode("code")}let i;try{i=this.loadModeFile(n),u.debug("SYSTEM",`Loaded override file: ${n} for parent ${s}`)}catch(d){return d instanceof Error?u.warn("WORKER",`Override file '${n}' not found, using parent mode '${s}' only`,{message:d.message}):u.warn("WORKER",`Override file '${n}' not found, using parent mode '${s}' only`,{error:String(d)}),this.activeMode=o,o}if(!i)return u.warn("SYSTEM",`Invalid override file: ${n}, using parent mode '${s}' only`),this.activeMode=o,o;let a=this.deepMerge(o,i);return this.activeMode=a,u.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${s} + ${n})`,void 0,{parent:s,override:n,types:a.observation_types.map(d=>d.id),concepts:a.observation_concepts.map(d=>d.id)}),a}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getObservationConcepts(){return this.getActiveMode().observation_concepts}getTypeIcon(e){return this.getObservationTypes().find(s=>s.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(s=>s.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(t=>t.id===e)}getTypeLabel(e){return this.getObservationTypes().find(s=>s.id===e)?.label||e}};function de(){let r=x.settings(),e=V.loadFromFile(r),t=C.getInstance().getActiveMode(),s=new Set(t.observation_types.map(o=>o.id)),n=new Set(t.observation_concepts.map(o=>o.id));return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:s,observationConcepts:n,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}var _={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},Pe=4,_e=1;function ue(r){let e=(r.title?.length||0)+(r.subtitle?.length||0)+(r.narrative?.length||0)+JSON.stringify(r.facts||[]).length;return Math.ceil(e/Pe)}function pe(r){let e=r.length,t=r.reduce((i,a)=>i+ue(a),0),s=r.reduce((i,a)=>i+(a.discovery_tokens||0),0),n=s-t,o=s>0?Math.round(n/s*100):0;return{totalObservations:e,totalReadTokens:t,totalDiscoveryTokens:s,savings:n,savingsPercent:o}}function ts(r){return C.getInstance().getWorkEmoji(r)}function F(r,e){let t=ue(r),s=r.discovery_tokens||0,n=ts(r.type),o=s>0?`${n} ${s.toLocaleString()}`:"-";return{readTokens:t,discoveryTokens:s,discoveryDisplay:o,workEmoji:n}}function q(r){return r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent}var $e=U(require("path"),1),K=require("fs");var ss=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],ar=new RegExp(`<(${ss.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),Fe=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var rs=["task-notification"],dr=new RegExp(`^\\s*<(${rs.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),_r=256*1024;function ce(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(",");return r.db.prepare(`
|
|
696
709
|
SELECT
|
|
697
710
|
o.id,
|
|
698
711
|
o.memory_session_id,
|
|
@@ -718,7 +731,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
718
731
|
)
|
|
719
732
|
ORDER BY o.created_at_epoch DESC
|
|
720
733
|
LIMIT ?
|
|
721
|
-
`).all(e,e,...s,...o,t.totalObservationCount)}function
|
|
734
|
+
`).all(e,e,...s,...o,t.totalObservationCount)}function me(r,e,t){return r.db.prepare(`
|
|
722
735
|
SELECT
|
|
723
736
|
ss.id,
|
|
724
737
|
ss.memory_session_id,
|
|
@@ -735,7 +748,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
735
748
|
WHERE (ss.project = ? OR ss.merged_into_project = ?)
|
|
736
749
|
ORDER BY ss.created_at_epoch DESC
|
|
737
750
|
LIMIT ?
|
|
738
|
-
`).all(e,e,t.sessionCount+_e)}function
|
|
751
|
+
`).all(e,e,t.sessionCount+_e)}function He(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(","),a=e.map(()=>"?").join(",");return r.db.prepare(`
|
|
739
752
|
SELECT
|
|
740
753
|
o.id,
|
|
741
754
|
o.memory_session_id,
|
|
@@ -763,7 +776,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
763
776
|
)
|
|
764
777
|
ORDER BY o.created_at_epoch DESC
|
|
765
778
|
LIMIT ?
|
|
766
|
-
`).all(...e,...e,...s,...o,t.totalObservationCount)}function
|
|
779
|
+
`).all(...e,...e,...s,...o,t.totalObservationCount)}function je(r,e,t){let s=e.map(()=>"?").join(",");return r.db.prepare(`
|
|
767
780
|
SELECT
|
|
768
781
|
ss.id,
|
|
769
782
|
ss.memory_session_id,
|
|
@@ -782,14 +795,14 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
782
795
|
OR ss.merged_into_project IN (${s}))
|
|
783
796
|
ORDER BY ss.created_at_epoch DESC
|
|
784
797
|
LIMIT ?
|
|
785
|
-
`).all(...e,...e,t.sessionCount+_e)}function Ge(r){return r.replace(/[/.]/g,"-")}function
|
|
786
|
-
`).filter(n=>n.trim());return{userMessage:"",assistantMessage:
|
|
798
|
+
`).all(...e,...e,t.sessionCount+_e)}function Ge(r){return r.replace(/[/.]/g,"-")}function ns(r){if(!r.includes('"type":"assistant"'))return null;let e=JSON.parse(r);if(e.type==="assistant"&&e.message?.content&&Array.isArray(e.message.content)){let t="";for(let s of e.message.content)s.type==="text"&&(t+=s.text);if(t=t.replace(Fe,"").trim(),t)return t}return null}function os(r){for(let e=r.length-1;e>=0;e--)try{let t=ns(r[e]);if(t)return t}catch(t){t instanceof Error?u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e},t):u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e,error:String(t)});continue}return""}function is(r){try{if(!(0,K.existsSync)(r))return{userMessage:"",assistantMessage:""};let e=(0,K.readFileSync)(r,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(`
|
|
799
|
+
`).filter(n=>n.trim());return{userMessage:"",assistantMessage:os(t)}}catch(e){return e instanceof Error?u.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e):u.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r,error:String(e)}),{userMessage:"",assistantMessage:""}}}function le(r,e,t,s){if(!e.showLastMessage||r.length===0)return{userMessage:"",assistantMessage:""};let n=r.find(d=>d.memory_session_id!==t);if(!n)return{userMessage:"",assistantMessage:""};let o=n.memory_session_id,i=Ge(s),a=$e.default.join(v,"projects",i,`${o}.jsonl`);return is(a)}function Xe(r,e){let t=e[0]?.id;return r.map((s,n)=>{let o=n===0?null:e[n+1];return{...s,displayEpoch:o?o.created_at_epoch:s.created_at_epoch,displayTime:o?o.created_at:s.created_at,shouldShowLink:s.id!==t}})}function Ee(r,e){let t=[...r.map(s=>({type:"observation",data:s})),...e.map(s=>({type:"summary",data:s}))];return t.sort((s,n)=>{let o=s.type==="observation"?s.data.created_at_epoch:s.data.displayEpoch,i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch;return o-i}),t}function Be(r,e){return new Set(r.slice(0,e).map(t=>t.id))}function We(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function Ve(r){return[`# [${r}] recent context, ${We()}`,""]}function Ye(){return[`Legend: \u{1F3AF}session ${C.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji}${t.id}`).join(" ")}`,"Format: ID TIME TYPE TITLE","Fetch details: get_observations([IDs]) | Search: mem-search skill",""]}function qe(){return[]}function Ke(){return[]}function Je(r,e){let t=[],s=[`${r.totalObservations} obs (${r.totalReadTokens.toLocaleString()}t read)`,`${r.totalDiscoveryTokens.toLocaleString()}t work`];return r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)&&(e.showSavingsPercent?s.push(`${r.savingsPercent}% savings`):e.showSavingsAmount&&s.push(`${r.savings.toLocaleString()}t saved`)),t.push(`Stats: ${s.join(" | ")}`),t.push(""),t}function Qe(r){return[`### ${r}`]}function ze(r){return r.toLowerCase().replace(" am","a").replace(" pm","p")}function Ze(r,e,t){let s=r.title||"Untitled",n=C.getInstance().getTypeIcon(r.type),o=e?ze(e):'"';return`${r.id} ${o} ${n} ${s}`}function et(r,e,t,s){let n=[],o=r.title||"Untitled",i=C.getInstance().getTypeIcon(r.type),a=e?ze(e):'"',{readTokens:d,discoveryDisplay:c}=F(r,s);n.push(`**${r.id}** ${a} ${i} **${o}**`),t&&n.push(t);let p=[];return s.showReadTokens&&p.push(`~${d}t`),s.showWorkTokens&&p.push(c),p.length>0&&n.push(p.join(" ")),n.push(""),n}function tt(r,e){return[`S${r.id} ${r.request||"Session started"} (${e})`]}function $(r,e){return e?[`**${r}**: ${e}`,""]:[]}function st(r){return r.assistantMessage?["","---","","**Previously**","",`A: ${r.assistantMessage}`,""]:[]}function rt(r,e){return["",`Access ${Math.round(r/1e3)}k tokens of past work via get_observations([IDs]) or mem-search skill.`]}function nt(r){return`# [${r}] recent context, ${We()}
|
|
787
800
|
|
|
788
|
-
No previous sessions found.`}function
|
|
789
|
-
${_.bright}${_.cyan}[${r}] recent context, ${
|
|
801
|
+
No previous sessions found.`}function ot(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function it(r){return["",`${_.bright}${_.cyan}[${r}] recent context, ${ot()}${_.reset}`,`${_.gray}${"\u2500".repeat(60)}${_.reset}`,""]}function at(){let e=C.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ");return[`${_.dim}Legend: session-request | ${e}${_.reset}`,""]}function dt(){return[`${_.bright}Column Key${_.reset}`,`${_.dim} Read: Tokens to read this observation (cost to learn it now)${_.reset}`,`${_.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${_.reset}`,""]}function _t(){return[`${_.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${_.reset}`,"",`${_.dim}When you need implementation details, rationale, or debugging context:${_.reset}`,`${_.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${_.reset}`,`${_.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${_.reset}`,`${_.dim} - Trust this index over re-reading code for past decisions and learnings${_.reset}`,""]}function ut(r,e){let t=[];if(t.push(`${_.bright}${_.cyan}Context Economics${_.reset}`),t.push(`${_.dim} Loading: ${r.totalObservations} observations (${r.totalReadTokens.toLocaleString()} tokens to read)${_.reset}`),t.push(`${_.dim} Work investment: ${r.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${_.reset}`),r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let s=" Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?s+=`${r.savings.toLocaleString()} tokens (${r.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?s+=`${r.savings.toLocaleString()} tokens`:s+=`${r.savingsPercent}% reduction from reuse`,t.push(`${_.green}${s}${_.reset}`)}return t.push(""),t}function pt(r){return[`${_.bright}${_.cyan}${r}${_.reset}`,""]}function ct(r){return[`${_.dim}${r}${_.reset}`]}function mt(r,e,t,s){let n=r.title||"Untitled",o=C.getInstance().getTypeIcon(r.type),{readTokens:i,discoveryTokens:a,workEmoji:d}=F(r,s),c=t?`${_.dim}${e}${_.reset}`:" ".repeat(e.length),p=s.showReadTokens&&i>0?`${_.dim}(~${i}t)${_.reset}`:"",T=s.showWorkTokens&&a>0?`${_.dim}(${d} ${a.toLocaleString()}t)${_.reset}`:"";return` ${_.dim}#${r.id}${_.reset} ${c} ${o} ${n} ${p} ${T}`}function lt(r,e,t,s,n){let o=[],i=r.title||"Untitled",a=C.getInstance().getTypeIcon(r.type),{readTokens:d,discoveryTokens:c,workEmoji:p}=F(r,n),T=t?`${_.dim}${e}${_.reset}`:" ".repeat(e.length),l=n.showReadTokens&&d>0?`${_.dim}(~${d}t)${_.reset}`:"",E=n.showWorkTokens&&c>0?`${_.dim}(${p} ${c.toLocaleString()}t)${_.reset}`:"";return o.push(` ${_.dim}#${r.id}${_.reset} ${T} ${a} ${_.bright}${i}${_.reset}`),s&&o.push(` ${_.dim}${s}${_.reset}`),(l||E)&&o.push(` ${l} ${E}`),o.push(""),o}function Et(r,e){let t=`${r.request||"Session started"} (${e})`;return[`${_.yellow}#S${r.id}${_.reset} ${t}`,""]}function H(r,e,t){return e?[`${t}${r}:${_.reset} ${e}`,""]:[]}function gt(r){return r.assistantMessage?["","---","",`${_.bright}${_.magenta}Previously${_.reset}`,"",`${_.dim}A: ${r.assistantMessage}${_.reset}`,""]:[]}function Tt(r,e){let t=Math.round(r/1e3);return["",`${_.dim}Access ${t}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use the claude-mem skill to access memories by ID.${_.reset}`]}function ft(r){return`
|
|
802
|
+
${_.bright}${_.cyan}[${r}] recent context, ${ot()}${_.reset}
|
|
790
803
|
${_.gray}${"\u2500".repeat(60)}${_.reset}
|
|
791
804
|
|
|
792
805
|
${_.dim}No previous sessions found for this project yet.${_.reset}
|
|
793
|
-
`}function
|
|
794
|
-
`):null}function
|
|
795
|
-
`).trimEnd()}async function Se(r,e=!1){let t=de(),s=r?.cwd??process.cwd(),n=ne(s),o=r?.projects?.length?r.projects:n.allProjects,i=o[o.length-1]??n.primary;r?.full&&(t.totalObservationCount=999999,t.sessionCount=999999);let a=cs();if(!a)return"";try{let d=o.length>1?
|
|
806
|
+
`}function St(r,e,t,s){let n=[];return s?n.push(...it(r)):n.push(...Ve(r)),s?n.push(...at()):n.push(...Ye()),s?n.push(...dt()):n.push(...qe()),s?n.push(..._t()):n.push(...Ke()),q(t)&&(s?n.push(...ut(e,t)):n.push(...Je(e,t))),n}var ge=U(require("path"),1);function z(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return u.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e instanceof Error?e:new Error(String(e))),[]}}function Te(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function fe(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Ot(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function bt(r,e){return ge.default.isAbsolute(r)?ge.default.relative(e,r):r}function Rt(r,e,t){let s=z(r);if(s.length>0)return bt(s[0],e);if(t){let n=z(t);if(n.length>0)return bt(n[0],e)}return"General"}function as(r){let e=new Map;for(let s of r){let n=s.type==="observation"?s.data.created_at:s.data.displayTime,o=Ot(n);e.has(o)||e.set(o,[]),e.get(o).push(s)}let t=Array.from(e.entries()).sort((s,n)=>{let o=new Date(s[0]).getTime(),i=new Date(n[0]).getTime();return o-i});return new Map(t)}function ht(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?z(r.facts).join(`
|
|
807
|
+
`):null}function ds(r,e,t,s){let n=[];n.push(...Qe(r));let o="";for(let i of e)if(i.type==="summary"){let a=i.data,d=Te(a.displayTime);n.push(...tt(a,d))}else{let a=i.data,d=fe(a.created_at),p=d!==o?d:"";if(o=d,t.has(a.id)){let l=ht(a,s);n.push(...et(a,p,l,s))}else n.push(Ze(a,p,s))}return n}function _s(r,e,t,s,n){let o=[];o.push(...pt(r));let i=null,a="";for(let d of e)if(d.type==="summary"){i=null,a="";let c=d.data,p=Te(c.displayTime);o.push(...Et(c,p))}else{let c=d.data,p=Rt(c.files_modified,n,c.files_read),T=fe(c.created_at),l=T!==a;a=T;let E=t.has(c.id);if(p!==i&&(o.push(...ct(p)),i=p),E){let f=ht(c,s);o.push(...lt(c,T,l,f,s))}else o.push(mt(c,T,l,s))}return o.push(""),o}function us(r,e,t,s,n,o){return o?_s(r,e,t,s,n):ds(r,e,t,s)}function At(r,e,t,s,n){let o=[],i=as(r);for(let[a,d]of i)o.push(...us(a,d,e,t,s,n));return o}function Nt(r,e,t){return!(!r.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||t&&e.created_at_epoch<=t.created_at_epoch)}function Ct(r,e){let t=[];return e?(t.push(...H("Investigated",r.investigated,_.blue)),t.push(...H("Learned",r.learned,_.yellow)),t.push(...H("Completed",r.completed,_.green)),t.push(...H("Next Steps",r.next_steps,_.magenta))):(t.push(...$("Investigated",r.investigated)),t.push(...$("Learned",r.learned)),t.push(...$("Completed",r.completed)),t.push(...$("Next Steps",r.next_steps))),t}function It(r,e){return e?gt(r):st(r)}function Lt(r,e,t){return!q(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?Tt(r.totalDiscoveryTokens,r.totalReadTokens):rt(r.totalDiscoveryTokens,r.totalReadTokens)}var ps=Mt.default.join((0,Dt.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function cs(){try{return new W}catch(r){if(r instanceof Error&&r.code==="ERR_DLOPEN_FAILED"){try{(0,vt.unlinkSync)(ps)}catch(e){e instanceof Error?u.debug("WORKER","Marker file cleanup failed (may not exist)",{},e):u.debug("WORKER","Marker file cleanup failed (may not exist)",{error:String(e)})}return u.error("WORKER","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function ms(r,e){return e?ft(r):nt(r)}function ls(r,e,t,s,n,o,i){let a=[],d=pe(e);a.push(...St(r,d,s,i));let c=t.slice(0,s.sessionCount),p=Xe(c,t),T=Ee(e,p),l=Be(e,s.fullObservationCount);a.push(...At(T,l,s,n,i));let E=t[0],f=e[0];Nt(s,E,f)&&a.push(...Ct(E,i));let b=le(e,s,o,n);return a.push(...It(b,i)),a.push(...Lt(d,s,i)),a.join(`
|
|
808
|
+
`).trimEnd()}async function Se(r,e=!1){let t=de(),s=r?.cwd??process.cwd(),n=ne(s),o=r?.projects?.length?r.projects:n.allProjects,i=o[o.length-1]??n.primary;r?.full&&(t.totalObservationCount=999999,t.sessionCount=999999);let a=cs();if(!a)return"";try{let d=o.length>1?He(a,o,t):ce(a,i,t),c=o.length>1?je(a,o,t):me(a,i,t);return d.length===0&&c.length===0?ms(i,e):ls(i,d,c,t,s,r?.session_id,e)}finally{a.close()}}0&&(module.exports={generateContext});
|