claude-mem 10.7.2 → 12.0.0

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.
@@ -1,12 +1,12 @@
1
- "use strict";var Tt=Object.create;var x=Object.defineProperty;var gt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var St=Object.getPrototypeOf,bt=Object.prototype.hasOwnProperty;var ht=(r,e)=>{for(var t in e)x(r,t,{get:e[t],enumerable:!0})},de=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ft(e))!bt.call(r,n)&&n!==t&&x(r,n,{get:()=>e[n],enumerable:!(s=gt(e,n))||s.enumerable});return r};var M=(r,e,t)=>(t=r!=null?Tt(St(r)):{},de(e||!r||!r.__esModule?x(t,"default",{value:r,enumerable:!0}):t,r)),Ot=r=>de(x({},"__esModule",{value:!0}),r);var Pt={};ht(Pt,{generateContext:()=>ae});module.exports=Ot(Pt);var mt=M(require("path"),1),ut=require("os"),lt=require("fs");var Te=require("bun:sqlite");var b=require("path"),K=require("os"),k=require("fs");var pe=require("url");var I=require("fs"),L=require("path"),ce=require("os"),q=(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))(q||{}),_e=(0,L.join)((0,ce.homedir)(),".claude-mem"),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=(0,L.join)(_e,"logs");(0,I.existsSync)(e)||(0,I.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,L.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=(0,L.join)(_e,"settings.json");if((0,I.existsSync)(e)){let t=(0,I.readFileSync)(e,"utf-8"),n=(JSON.parse(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=q[n]??1}else this.level=1}catch{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=q[e].padEnd(5),d=t.padEnd(6),c="";n?.correlationId?c=`[${n.correlationId}] `:n?.sessionId&&(c=`[session-${n.sessionId}] `);let m="";o!=null&&(o instanceof Error?m=this.getLevel()===0?`
1
+ "use strict";var At=Object.create;var F=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var Nt=Object.getOwnPropertyNames;var Ct=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var Lt=(r,e)=>{for(var t in e)F(r,t,{get:e[t],enumerable:!0})},pe=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Nt(e))!It.call(r,n)&&n!==t&&F(r,n,{get:()=>e[n],enumerable:!(s=Rt(e,n))||s.enumerable});return r};var D=(r,e,t)=>(t=r!=null?At(Ct(r)):{},pe(e||!r||!r.__esModule?F(t,"default",{value:r,enumerable:!0}):t,r)),yt=r=>pe(F({},"__esModule",{value:!0}),r);var Kt={};Lt(Kt,{generateContext:()=>me});module.exports=yt(Kt);var St=D(require("path"),1),bt=require("os"),ht=require("fs");var Oe=require("bun:sqlite");var f=require("path"),z=require("os"),w=require("fs");var ge=require("url");var I=require("fs"),M=require("path"),Ee=require("os"),K=(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))(K||{}),le=(0,M.join)((0,Ee.homedir)(),".claude-mem"),J=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=(0,M.join)(le,"logs");(0,I.existsSync)(e)||(0,I.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,M.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=(0,M.join)(le,"settings.json");if((0,I.existsSync)(e)){let t=(0,I.readFileSync)(e,"utf-8"),n=(JSON.parse(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=K[n]??1}else this.level=1}catch{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=K[e].padEnd(5),d=t.padEnd(6),u="";n?.correlationId?u=`[${n.correlationId}] `:n?.sessionId&&(u=`[session-${n.sessionId}] `);let _="";o!=null&&(o instanceof Error?_=this.getLevel()===0?`
3
3
  ${o.message}
4
- ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
5
- `+JSON.stringify(o,null,2):m=" "+this.formatData(o));let l="";if(n){let{sessionId:E,memorySessionId:f,correlationId:R,...u}=n;Object.keys(u).length>0&&(l=` {${Object.entries(u).map(([g,h])=>`${g}=${h}`).join(", ")}}`)}let T=`[${i}] [${a}] [${d}] ${c}${s}${l}${m}`;if(this.logFilePath)try{(0,I.appendFileSync)(this.logFilePath,T+`
6
- `,"utf8")}catch(E){process.stderr.write(`[LOGGER] Failed to write to log file: ${E}
7
- `)}else process.stderr.write(T+`
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+)\)?/),m=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",l={...s,location:m};return this.warn(e,`[HAPPY-PATH] ${t}`,l,n),o}},p=new V;var It={};function Rt(){return typeof __dirname<"u"?__dirname:(0,b.dirname)((0,pe.fileURLToPath)(It.url))}var Ct=Rt();function Nt(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let r=(0,b.join)((0,K.homedir)(),".claude-mem"),e=(0,b.join)(r,"settings.json");try{if((0,k.existsSync)(e)){let{readFileSync:t}=require("fs"),s=JSON.parse(t(e,"utf-8")),n=s.env??s;if(n.CLAUDE_MEM_DATA_DIR)return n.CLAUDE_MEM_DATA_DIR}}catch{}return r}var C=Nt(),A=process.env.CLAUDE_CONFIG_DIR||(0,b.join)((0,K.homedir)(),".claude"),Bt=(0,b.join)(A,"plugins","marketplaces","thedotmack"),Wt=(0,b.join)(C,"archives"),Yt=(0,b.join)(C,"logs"),qt=(0,b.join)(C,"trash"),Vt=(0,b.join)(C,"backups"),Kt=(0,b.join)(C,"modes"),Jt=(0,b.join)(C,"settings.json"),me=(0,b.join)(C,"claude-mem.db"),Qt=(0,b.join)(C,"vector-db"),zt=(0,b.join)(C,"observer-sessions"),Zt=(0,b.join)(A,"settings.json"),es=(0,b.join)(A,"commands"),ts=(0,b.join)(A,"CLAUDE.md");function ue(r){(0,k.mkdirSync)(r,{recursive:!0})}function le(){return(0,b.join)(Ct,"..")}var Ee=require("crypto");var At=3e4;function w(r,e,t){return(0,Ee.createHash)("sha256").update((r||"")+(e||"")+(t||"")).digest("hex").slice(0,16)}function $(r,e,t){let s=t-At;return r.prepare("SELECT id, created_at_epoch FROM observations WHERE content_hash = ? AND created_at_epoch > ?").get(e,s)}var F=class{db;constructor(e=me){e!==":memory:"&&ue(C),this.db=new Te.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA foreign_keys = ON"),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()}initializeSchema(){this.db.run(`
4
+ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?_=`
5
+ `+JSON.stringify(o,null,2):_=" "+this.formatData(o));let l="";if(n){let{sessionId:T,memorySessionId:O,correlationId:S,...p}=n;Object.keys(p).length>0&&(l=` {${Object.entries(p).map(([g,b])=>`${g}=${b}`).join(", ")}}`)}let E=`[${i}] [${a}] [${d}] ${u}${s}${l}${_}`;if(this.logFilePath)try{(0,I.appendFileSync)(this.logFilePath,E+`
6
+ `,"utf8")}catch(T){process.stderr.write(`[LOGGER] Failed to write to log file: ${T}
7
+ `)}else process.stderr.write(E+`
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 u=((new Error().stack||"").split(`
9
+ `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),_=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",l={...s,location:_};return this.warn(e,`[HAPPY-PATH] ${t}`,l,n),o}},m=new J;var Ut={};function Dt(){return typeof __dirname<"u"?__dirname:(0,f.dirname)((0,ge.fileURLToPath)(Ut.url))}var Mt=Dt();function vt(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let r=(0,f.join)((0,z.homedir)(),".claude-mem"),e=(0,f.join)(r,"settings.json");try{if((0,w.existsSync)(e)){let{readFileSync:t}=require("fs"),s=JSON.parse(t(e,"utf-8")),n=s.env??s;if(n.CLAUDE_MEM_DATA_DIR)return n.CLAUDE_MEM_DATA_DIR}}catch{}return r}var N=vt(),L=process.env.CLAUDE_CONFIG_DIR||(0,f.join)((0,z.homedir)(),".claude"),es=(0,f.join)(L,"plugins","marketplaces","thedotmack"),ts=(0,f.join)(N,"archives"),ss=(0,f.join)(N,"logs"),rs=(0,f.join)(N,"trash"),ns=(0,f.join)(N,"backups"),os=(0,f.join)(N,"modes"),is=(0,f.join)(N,"settings.json"),Te=(0,f.join)(N,"claude-mem.db"),as=(0,f.join)(N,"vector-db"),ds=(0,f.join)(N,"observer-sessions"),cs=(0,f.join)(L,"settings.json"),us=(0,f.join)(L,"commands"),ms=(0,f.join)(L,"CLAUDE.md");function fe(r){(0,w.mkdirSync)(r,{recursive:!0})}function Se(){return(0,f.join)(Mt,"..")}var be=require("crypto");var xt=3e4;function P(r,e,t){return(0,be.createHash)("sha256").update([r||"",e||"",t||""].join("\0")).digest("hex").slice(0,16)}function H(r,e,t){let s=t-xt;return r.prepare("SELECT id, created_at_epoch FROM observations WHERE content_hash = ? AND created_at_epoch > ?").get(e,s)}function Q(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[String(e)]}catch{return[r]}}var h="claude";function kt(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function y(r){if(!r)return h;let e=kt(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:h}function he(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 $t(r,e){return{customTitle:r,platformSource:e?y(e):void 0}}var X=class{db;constructor(e=Te){e!==":memory:"&&fe(N),this.db=new Oe.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA foreign_keys = ON"),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()}initializeSchema(){this.db.run(`
10
10
  CREATE TABLE IF NOT EXISTS schema_versions (
11
11
  id INTEGER PRIMARY KEY,
12
12
  version INTEGER UNIQUE NOT NULL,
@@ -18,6 +18,7 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
18
18
  content_session_id TEXT UNIQUE NOT NULL,
19
19
  memory_session_id TEXT UNIQUE,
20
20
  project TEXT NOT NULL,
21
+ platform_source TEXT NOT NULL DEFAULT 'claude',
21
22
  user_prompt TEXT,
22
23
  started_at TEXT NOT NULL,
23
24
  started_at_epoch INTEGER NOT NULL,
@@ -68,7 +69,7 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
68
69
  CREATE INDEX IF NOT EXISTS idx_session_summaries_sdk_session ON session_summaries(memory_session_id);
69
70
  CREATE INDEX IF NOT EXISTS idx_session_summaries_project ON session_summaries(project);
70
71
  CREATE INDEX IF NOT EXISTS idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
71
- `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(4,new Date().toISOString())}ensureWorkerPortColumn(){this.db.query("PRAGMA table_info(sdk_sessions)").all().some(s=>s.name==="worker_port")||(this.db.run("ALTER TABLE sdk_sessions ADD COLUMN worker_port INTEGER"),p.debug("DB","Added worker_port column to sdk_sessions table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(5,new Date().toISOString())}ensurePromptTrackingColumns(){this.db.query("PRAGMA table_info(sdk_sessions)").all().some(a=>a.name==="prompt_counter")||(this.db.run("ALTER TABLE sdk_sessions ADD COLUMN prompt_counter INTEGER DEFAULT 0"),p.debug("DB","Added prompt_counter column to sdk_sessions table")),this.db.query("PRAGMA table_info(observations)").all().some(a=>a.name==="prompt_number")||(this.db.run("ALTER TABLE observations ADD COLUMN prompt_number INTEGER"),p.debug("DB","Added prompt_number column to observations table")),this.db.query("PRAGMA table_info(session_summaries)").all().some(a=>a.name==="prompt_number")||(this.db.run("ALTER TABLE session_summaries ADD COLUMN prompt_number INTEGER"),p.debug("DB","Added prompt_number column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(6,new Date().toISOString())}removeSessionSummariesUniqueConstraint(){if(!this.db.query("PRAGMA index_list(session_summaries)").all().some(s=>s.unique===1)){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString());return}p.debug("DB","Removing UNIQUE constraint from session_summaries.memory_session_id"),this.db.run("BEGIN TRANSACTION"),this.db.run("DROP TABLE IF EXISTS session_summaries_new"),this.db.run(`
72
+ `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(4,new Date().toISOString())}ensureWorkerPortColumn(){this.db.query("PRAGMA table_info(sdk_sessions)").all().some(s=>s.name==="worker_port")||(this.db.run("ALTER TABLE sdk_sessions ADD COLUMN worker_port INTEGER"),m.debug("DB","Added worker_port column to sdk_sessions table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(5,new Date().toISOString())}ensurePromptTrackingColumns(){this.db.query("PRAGMA table_info(sdk_sessions)").all().some(a=>a.name==="prompt_counter")||(this.db.run("ALTER TABLE sdk_sessions ADD COLUMN prompt_counter INTEGER DEFAULT 0"),m.debug("DB","Added prompt_counter column to sdk_sessions table")),this.db.query("PRAGMA table_info(observations)").all().some(a=>a.name==="prompt_number")||(this.db.run("ALTER TABLE observations ADD COLUMN prompt_number INTEGER"),m.debug("DB","Added prompt_number column to observations table")),this.db.query("PRAGMA table_info(session_summaries)").all().some(a=>a.name==="prompt_number")||(this.db.run("ALTER TABLE session_summaries ADD COLUMN prompt_number INTEGER"),m.debug("DB","Added prompt_number column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(6,new Date().toISOString())}removeSessionSummariesUniqueConstraint(){if(!this.db.query("PRAGMA index_list(session_summaries)").all().some(s=>s.unique===1)){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString());return}m.debug("DB","Removing UNIQUE constraint from session_summaries.memory_session_id"),this.db.run("BEGIN TRANSACTION"),this.db.run("DROP TABLE IF EXISTS session_summaries_new"),this.db.run(`
72
73
  CREATE TABLE session_summaries_new (
73
74
  id INTEGER PRIMARY KEY AUTOINCREMENT,
74
75
  memory_session_id TEXT NOT NULL,
@@ -96,7 +97,7 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
96
97
  CREATE INDEX idx_session_summaries_sdk_session ON session_summaries(memory_session_id);
97
98
  CREATE INDEX idx_session_summaries_project ON session_summaries(project);
98
99
  CREATE INDEX idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
99
- `),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString()),p.debug("DB","Successfully removed UNIQUE constraint from session_summaries.memory_session_id")}addObservationHierarchicalFields(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(8))return;if(this.db.query("PRAGMA table_info(observations)").all().some(n=>n.name==="title")){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString());return}p.debug("DB","Adding hierarchical fields to observations table"),this.db.run(`
100
+ `),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString()),m.debug("DB","Successfully removed UNIQUE constraint from session_summaries.memory_session_id")}addObservationHierarchicalFields(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(8))return;if(this.db.query("PRAGMA table_info(observations)").all().some(n=>n.name==="title")){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString());return}m.debug("DB","Adding hierarchical fields to observations table"),this.db.run(`
100
101
  ALTER TABLE observations ADD COLUMN title TEXT;
101
102
  ALTER TABLE observations ADD COLUMN subtitle TEXT;
102
103
  ALTER TABLE observations ADD COLUMN facts TEXT;
@@ -104,7 +105,7 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
104
105
  ALTER TABLE observations ADD COLUMN concepts TEXT;
105
106
  ALTER TABLE observations ADD COLUMN files_read TEXT;
106
107
  ALTER TABLE observations ADD COLUMN files_modified TEXT;
107
- `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString()),p.debug("DB","Successfully added hierarchical fields to observations table")}makeObservationsTextNullable(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(9))return;let s=this.db.query("PRAGMA table_info(observations)").all().find(n=>n.name==="text");if(!s||s.notnull===0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString());return}p.debug("DB","Making observations.text nullable"),this.db.run("BEGIN TRANSACTION"),this.db.run("DROP TABLE IF EXISTS observations_new"),this.db.run(`
108
+ `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString()),m.debug("DB","Successfully added hierarchical fields to observations table")}makeObservationsTextNullable(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(9))return;let s=this.db.query("PRAGMA table_info(observations)").all().find(n=>n.name==="text");if(!s||s.notnull===0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString());return}m.debug("DB","Making observations.text nullable"),this.db.run("BEGIN TRANSACTION"),this.db.run("DROP TABLE IF EXISTS observations_new"),this.db.run(`
108
109
  CREATE TABLE observations_new (
109
110
  id INTEGER PRIMARY KEY AUTOINCREMENT,
110
111
  memory_session_id TEXT NOT NULL,
@@ -134,7 +135,7 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
134
135
  CREATE INDEX idx_observations_project ON observations(project);
135
136
  CREATE INDEX idx_observations_type ON observations(type);
136
137
  CREATE INDEX idx_observations_created ON observations(created_at_epoch DESC);
137
- `),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString()),p.debug("DB","Successfully made observations.text nullable")}createUserPromptsTable(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(10))return;if(this.db.query("PRAGMA table_info(user_prompts)").all().length>0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString());return}p.debug("DB","Creating user_prompts table with FTS5 support"),this.db.run("BEGIN TRANSACTION"),this.db.run(`
138
+ `),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString()),m.debug("DB","Successfully made observations.text nullable")}createUserPromptsTable(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(10))return;if(this.db.query("PRAGMA table_info(user_prompts)").all().length>0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString());return}m.debug("DB","Creating user_prompts table with FTS5 support"),this.db.run("BEGIN TRANSACTION"),this.db.run(`
138
139
  CREATE TABLE user_prompts (
139
140
  id INTEGER PRIMARY KEY AUTOINCREMENT,
140
141
  content_session_id TEXT NOT NULL,
@@ -172,7 +173,7 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
172
173
  INSERT INTO user_prompts_fts(rowid, prompt_text)
173
174
  VALUES (new.id, new.prompt_text);
174
175
  END;
175
- `)}catch(s){p.warn("DB","FTS5 not available \u2014 user_prompts_fts skipped (search uses ChromaDB)",{},s)}this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString()),p.debug("DB","Successfully created user_prompts table")}ensureDiscoveryTokensColumn(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(11))return;this.db.query("PRAGMA table_info(observations)").all().some(i=>i.name==="discovery_tokens")||(this.db.run("ALTER TABLE observations ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),p.debug("DB","Added discovery_tokens column to observations table")),this.db.query("PRAGMA table_info(session_summaries)").all().some(i=>i.name==="discovery_tokens")||(this.db.run("ALTER TABLE session_summaries ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),p.debug("DB","Added discovery_tokens column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(11,new Date().toISOString())}createPendingMessagesTable(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(16))return;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(16,new Date().toISOString());return}p.debug("DB","Creating pending_messages table"),this.db.run(`
176
+ `)}catch(s){m.warn("DB","FTS5 not available \u2014 user_prompts_fts skipped (search uses ChromaDB)",{},s)}this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString()),m.debug("DB","Successfully created user_prompts table")}ensureDiscoveryTokensColumn(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(11))return;this.db.query("PRAGMA table_info(observations)").all().some(i=>i.name==="discovery_tokens")||(this.db.run("ALTER TABLE observations ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),m.debug("DB","Added discovery_tokens column to observations table")),this.db.query("PRAGMA table_info(session_summaries)").all().some(i=>i.name==="discovery_tokens")||(this.db.run("ALTER TABLE session_summaries ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),m.debug("DB","Added discovery_tokens column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(11,new Date().toISOString())}createPendingMessagesTable(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(16))return;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(16,new Date().toISOString());return}m.debug("DB","Creating pending_messages table"),this.db.run(`
176
177
  CREATE TABLE pending_messages (
177
178
  id INTEGER PRIMARY KEY AUTOINCREMENT,
178
179
  session_db_id INTEGER NOT NULL,
@@ -192,7 +193,7 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
192
193
  completed_at_epoch INTEGER,
193
194
  FOREIGN KEY (session_db_id) REFERENCES sdk_sessions(id) ON DELETE CASCADE
194
195
  )
195
- `),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()),p.debug("DB","pending_messages table created successfully")}renameSessionIdColumns(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(17))return;p.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(m=>m.name===o);return a.some(m=>m.name===i)?!1:d?(this.db.run(`ALTER TABLE ${n} RENAME COLUMN ${o} TO ${i}`),p.debug("DB",`Renamed ${n}.${o} to ${i}`),!0):(p.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?p.debug("DB",`Successfully renamed ${t} session ID columns`):p.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"),p.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)){p.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");try{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"),this.db.run(`
196
+ `),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()),m.debug("DB","pending_messages table created successfully")}renameSessionIdColumns(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(17))return;m.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(_=>_.name===o);return a.some(_=>_.name===i)?!1:d?(this.db.run(`ALTER TABLE ${n} RENAME COLUMN ${o} TO ${i}`),m.debug("DB",`Renamed ${n}.${o} to ${i}`),!0):(m.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?m.debug("DB",`Successfully renamed ${t} session ID columns`):m.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"),m.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)){m.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");try{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"),this.db.run(`
196
197
  CREATE TABLE observations_new (
197
198
  id INTEGER PRIMARY KEY AUTOINCREMENT,
198
199
  memory_session_id TEXT NOT NULL,
@@ -286,15 +287,23 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
286
287
  INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
287
288
  VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes);
288
289
  END;
289
- `),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"),p.debug("DB","Successfully added ON UPDATE CASCADE to FK constraints")}catch(t){throw this.db.run("ROLLBACK"),this.db.run("PRAGMA foreign_keys = ON"),t}}}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)"),p.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"),p.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())}updateMemorySessionId(e,t){this.db.prepare(`
290
+ `),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"),m.debug("DB","Successfully added ON UPDATE CASCADE to FK constraints")}catch(t){throw this.db.run("ROLLBACK"),this.db.run("PRAGMA foreign_keys = ON"),t}}}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)"),m.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"),m.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}'`),m.debug("DB","Added platform_source column to sdk_sessions table")),this.db.run(`
291
+ UPDATE sdk_sessions
292
+ SET platform_source = '${h}'
293
+ WHERE platform_source IS NULL OR platform_source = ''
294
+ `),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()))}updateMemorySessionId(e,t){this.db.prepare(`
290
295
  UPDATE sdk_sessions
291
296
  SET memory_session_id = ?
292
297
  WHERE id = ?
293
- `).run(t,e)}ensureMemorySessionIdRegistered(e,t){let s=this.db.prepare(`
298
+ `).run(t,e)}markSessionCompleted(e){let t=Date.now(),s=new Date(t).toISOString();this.db.prepare(`
299
+ UPDATE sdk_sessions
300
+ SET status = 'completed', completed_at = ?, completed_at_epoch = ?
301
+ WHERE id = ?
302
+ `).run(s,t,e)}ensureMemorySessionIdRegistered(e,t){let s=this.db.prepare(`
294
303
  SELECT id, memory_session_id FROM sdk_sessions WHERE id = ?
295
304
  `).get(e);if(!s)throw new Error(`Session ${e} not found in sdk_sessions`);s.memory_session_id!==t&&(this.db.prepare(`
296
305
  UPDATE sdk_sessions SET memory_session_id = ? WHERE id = ?
297
- `).run(t,e),p.info("DB","Registered memory_session_id before storage (FK fix)",{sessionDbId:e,oldId:s.memory_session_id,newId:t}))}getRecentSummaries(e,t=10){return this.db.prepare(`
306
+ `).run(t,e),m.info("DB","Registered memory_session_id before storage (FK fix)",{sessionDbId:e,oldId:s.memory_session_id,newId:t}))}getRecentSummaries(e,t=10){return this.db.prepare(`
298
307
  SELECT
299
308
  request, investigated, learned, completed, next_steps,
300
309
  files_read, files_edited, notes, prompt_number, created_at
@@ -317,22 +326,47 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
317
326
  ORDER BY created_at_epoch DESC
318
327
  LIMIT ?
319
328
  `).all(e,t)}getAllRecentObservations(e=100){return this.db.prepare(`
320
- SELECT id, type, title, subtitle, text, project, prompt_number, created_at, created_at_epoch
321
- FROM observations
322
- ORDER BY created_at_epoch DESC
329
+ SELECT
330
+ o.id,
331
+ o.type,
332
+ o.title,
333
+ o.subtitle,
334
+ o.text,
335
+ o.project,
336
+ COALESCE(s.platform_source, '${h}') as platform_source,
337
+ o.prompt_number,
338
+ o.created_at,
339
+ o.created_at_epoch
340
+ FROM observations o
341
+ LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
342
+ ORDER BY o.created_at_epoch DESC
323
343
  LIMIT ?
324
344
  `).all(e)}getAllRecentSummaries(e=50){return this.db.prepare(`
325
- SELECT id, request, investigated, learned, completed, next_steps,
326
- files_read, files_edited, notes, project, prompt_number,
327
- created_at, created_at_epoch
328
- FROM session_summaries
329
- ORDER BY created_at_epoch DESC
345
+ SELECT
346
+ ss.id,
347
+ ss.request,
348
+ ss.investigated,
349
+ ss.learned,
350
+ ss.completed,
351
+ ss.next_steps,
352
+ ss.files_read,
353
+ ss.files_edited,
354
+ ss.notes,
355
+ ss.project,
356
+ COALESCE(s.platform_source, '${h}') as platform_source,
357
+ ss.prompt_number,
358
+ ss.created_at,
359
+ ss.created_at_epoch
360
+ FROM session_summaries ss
361
+ LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
362
+ ORDER BY ss.created_at_epoch DESC
330
363
  LIMIT ?
331
364
  `).all(e)}getAllRecentUserPrompts(e=100){return this.db.prepare(`
332
365
  SELECT
333
366
  up.id,
334
367
  up.content_session_id,
335
368
  s.project,
369
+ COALESCE(s.platform_source, '${h}') as platform_source,
336
370
  up.prompt_number,
337
371
  up.prompt_text,
338
372
  up.created_at,
@@ -341,16 +375,25 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
341
375
  LEFT JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
342
376
  ORDER BY up.created_at_epoch DESC
343
377
  LIMIT ?
344
- `).all(e)}getAllProjects(){return this.db.prepare(`
378
+ `).all(e)}getAllProjects(e){let t=e?y(e):void 0,s=`
345
379
  SELECT DISTINCT project
346
380
  FROM sdk_sessions
347
381
  WHERE project IS NOT NULL AND project != ''
348
- ORDER BY project ASC
349
- `).all().map(s=>s.project)}getLatestUserPrompt(e){return this.db.prepare(`
382
+ `,n=[];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(`
383
+ SELECT
384
+ COALESCE(platform_source, '${h}') as platform_source,
385
+ project,
386
+ MAX(started_at_epoch) as latest_epoch
387
+ FROM sdk_sessions
388
+ WHERE project IS NOT NULL AND project != ''
389
+ GROUP BY COALESCE(platform_source, '${h}'), project
390
+ ORDER BY latest_epoch DESC
391
+ `).all(),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=he(Object.keys(n));return{projects:t,sources:o,projectsBySource:Object.fromEntries(o.map(i=>[i,n[i]||[]]))}}getLatestUserPrompt(e){return this.db.prepare(`
350
392
  SELECT
351
393
  up.*,
352
394
  s.memory_session_id,
353
- s.project
395
+ s.project,
396
+ COALESCE(s.platform_source, '${h}') as platform_source
354
397
  FROM user_prompts up
355
398
  JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
356
399
  WHERE up.content_session_id = ?
@@ -382,13 +425,13 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
382
425
  SELECT *
383
426
  FROM observations
384
427
  WHERE id = ?
385
- `).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==="date_asc"?"ASC":"DESC",m=n?`LIMIT ${n}`:"",l=e.map(()=>"?").join(","),T=[...e],E=[];if(o&&(E.push("project = ?"),T.push(o)),i)if(Array.isArray(i)){let u=i.map(()=>"?").join(",");E.push(`type IN (${u})`),T.push(...i)}else E.push("type = ?"),T.push(i);if(a){let u=Array.isArray(a)?a:[a],S=u.map(()=>"EXISTS (SELECT 1 FROM json_each(concepts) WHERE value = ?)");T.push(...u),E.push(`(${S.join(" OR ")})`)}if(d){let u=Array.isArray(d)?d:[d],S=u.map(()=>"(EXISTS (SELECT 1 FROM json_each(files_read) WHERE value LIKE ?) OR EXISTS (SELECT 1 FROM json_each(files_modified) WHERE value LIKE ?))");u.forEach(g=>{T.push(`%${g}%`,`%${g}%`)}),E.push(`(${S.join(" OR ")})`)}let f=E.length>0?`WHERE id IN (${l}) AND ${E.join(" AND ")}`:`WHERE id IN (${l})`;return this.db.prepare(`
428
+ `).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,u=s==="date_asc"?"ASC":"DESC",_=n?`LIMIT ${n}`:"",l=e.map(()=>"?").join(","),E=[...e],T=[];if(o&&(T.push("project = ?"),E.push(o)),i)if(Array.isArray(i)){let p=i.map(()=>"?").join(",");T.push(`type IN (${p})`),E.push(...i)}else T.push("type = ?"),E.push(i);if(a){let p=Array.isArray(a)?a:[a],R=p.map(()=>"EXISTS (SELECT 1 FROM json_each(concepts) WHERE value = ?)");E.push(...p),T.push(`(${R.join(" OR ")})`)}if(d){let p=Array.isArray(d)?d:[d],R=p.map(()=>"(EXISTS (SELECT 1 FROM json_each(files_read) WHERE value LIKE ?) OR EXISTS (SELECT 1 FROM json_each(files_modified) WHERE value LIKE ?))");p.forEach(g=>{E.push(`%${g}%`,`%${g}%`)}),T.push(`(${R.join(" OR ")})`)}let O=T.length>0?`WHERE id IN (${l}) AND ${T.join(" AND ")}`:`WHERE id IN (${l})`;return this.db.prepare(`
386
429
  SELECT *
387
430
  FROM observations
388
- ${f}
389
- ORDER BY created_at_epoch ${c}
390
- ${m}
391
- `).all(...T)}getSummaryForSession(e){return this.db.prepare(`
431
+ ${O}
432
+ ORDER BY created_at_epoch ${u}
433
+ ${_}
434
+ `).all(...E)}getSummaryForSession(e){return this.db.prepare(`
392
435
  SELECT
393
436
  request, investigated, learned, completed, next_steps,
394
437
  files_read, files_edited, notes, prompt_number, created_at,
@@ -401,32 +444,40 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
401
444
  SELECT files_read, files_modified
402
445
  FROM observations
403
446
  WHERE memory_session_id = ?
404
- `).all(e),n=new Set,o=new Set;for(let i of s){if(i.files_read){let a=JSON.parse(i.files_read);Array.isArray(a)&&a.forEach(d=>n.add(d))}if(i.files_modified){let a=JSON.parse(i.files_modified);Array.isArray(a)&&a.forEach(d=>o.add(d))}}return{filesRead:Array.from(n),filesModified:Array.from(o)}}getSessionById(e){return this.db.prepare(`
405
- SELECT id, content_session_id, memory_session_id, project, user_prompt, custom_title
447
+ `).all(e),n=new Set,o=new Set;for(let i of s)Q(i.files_read).forEach(a=>n.add(a)),Q(i.files_modified).forEach(a=>o.add(a));return{filesRead:Array.from(n),filesModified:Array.from(o)}}getSessionById(e){return this.db.prepare(`
448
+ SELECT id, content_session_id, memory_session_id, project,
449
+ COALESCE(platform_source, '${h}') as platform_source,
450
+ user_prompt, custom_title
406
451
  FROM sdk_sessions
407
452
  WHERE id = ?
408
453
  LIMIT 1
409
454
  `).get(e)||null}getSdkSessionsBySessionIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.db.prepare(`
410
- SELECT id, content_session_id, memory_session_id, project, user_prompt, custom_title,
455
+ SELECT id, content_session_id, memory_session_id, project,
456
+ COALESCE(platform_source, '${h}') as platform_source,
457
+ user_prompt, custom_title,
411
458
  started_at, started_at_epoch, completed_at, completed_at_epoch, status
412
459
  FROM sdk_sessions
413
460
  WHERE memory_session_id IN (${t})
414
461
  ORDER BY started_at_epoch DESC
415
462
  `).all(...e)}getPromptNumberFromUserPrompts(e){return this.db.prepare(`
416
463
  SELECT COUNT(*) as count FROM user_prompts WHERE content_session_id = ?
417
- `).get(e).count}createSDKSession(e,t,s,n){let o=new Date,i=o.getTime(),a=this.db.prepare(`
418
- SELECT id FROM sdk_sessions WHERE content_session_id = ?
419
- `).get(e);return a?(t&&this.db.prepare(`
464
+ `).get(e).count}createSDKSession(e,t,s,n,o){let i=new Date,a=i.getTime(),d=$t(n,o),u=d.platformSource??h,_=this.db.prepare(`
465
+ SELECT id, platform_source FROM sdk_sessions WHERE content_session_id = ?
466
+ `).get(e);if(_){if(t&&this.db.prepare(`
420
467
  UPDATE sdk_sessions SET project = ?
421
468
  WHERE content_session_id = ? AND (project IS NULL OR project = '')
422
- `).run(t,e),n&&this.db.prepare(`
469
+ `).run(t,e),d.customTitle&&this.db.prepare(`
423
470
  UPDATE sdk_sessions SET custom_title = ?
424
471
  WHERE content_session_id = ? AND custom_title IS NULL
425
- `).run(n,e),a.id):(this.db.prepare(`
472
+ `).run(d.customTitle,e),d.platformSource){let E=_.platform_source?.trim()?y(_.platform_source):void 0;if(!E)this.db.prepare(`
473
+ UPDATE sdk_sessions SET platform_source = ?
474
+ WHERE content_session_id = ?
475
+ AND COALESCE(platform_source, '') = ''
476
+ `).run(d.platformSource,e);else if(E!==d.platformSource)throw new Error(`Platform source conflict for session ${e}: existing=${E}, received=${d.platformSource}`)}return _.id}return this.db.prepare(`
426
477
  INSERT INTO sdk_sessions
427
- (content_session_id, memory_session_id, project, user_prompt, custom_title, started_at, started_at_epoch, status)
428
- VALUES (?, NULL, ?, ?, ?, ?, ?, 'active')
429
- `).run(e,t,s,n||null,o.toISOString(),i),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(`
478
+ (content_session_id, memory_session_id, project, platform_source, user_prompt, custom_title, started_at, started_at_epoch, status)
479
+ VALUES (?, NULL, ?, ?, ?, ?, ?, ?, 'active')
480
+ `).run(e,t,u,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(`
430
481
  INSERT INTO user_prompts
431
482
  (content_session_id, prompt_number, prompt_text, created_at, created_at_epoch)
432
483
  VALUES (?, ?, ?, ?, ?)
@@ -435,37 +486,40 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
435
486
  FROM user_prompts
436
487
  WHERE content_session_id = ? AND prompt_number = ?
437
488
  LIMIT 1
438
- `).get(e,t)?.prompt_text??null}storeObservation(e,t,s,n,o=0,i){let a=i??Date.now(),d=new Date(a).toISOString(),c=w(e,s.title,s.narrative),m=$(this.db,c,a);if(m)return{id:m.id,createdAtEpoch:m.created_at_epoch};let T=this.db.prepare(`
489
+ `).get(e,t)?.prompt_text??null}storeObservation(e,t,s,n,o=0,i,a){let d=i??Date.now(),u=new Date(d).toISOString(),_=P(e,s.title,s.narrative),l=H(this.db,_,d);if(l)return{id:l.id,createdAtEpoch:l.created_at_epoch};let T=this.db.prepare(`
439
490
  INSERT INTO observations
440
491
  (memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
441
- files_read, files_modified, prompt_number, discovery_tokens, content_hash, created_at, created_at_epoch)
442
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
443
- `).run(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,c,d,a);return{id:Number(T.lastInsertRowid),createdAtEpoch:a}}storeSummary(e,t,s,n,o=0,i){let a=i??Date.now(),d=new Date(a).toISOString(),m=this.db.prepare(`
492
+ files_read, files_modified, prompt_number, discovery_tokens, content_hash, created_at, created_at_epoch,
493
+ generated_by_model)
494
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
495
+ `).run(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,_,u,d,a||null);return{id:Number(T.lastInsertRowid),createdAtEpoch:d}}storeSummary(e,t,s,n,o=0,i){let a=i??Date.now(),d=new Date(a).toISOString(),_=this.db.prepare(`
444
496
  INSERT INTO session_summaries
445
497
  (memory_session_id, project, request, investigated, learned, completed,
446
498
  next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
447
499
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
448
- `).run(e,t,s.request,s.investigated,s.learned,s.completed,s.next_steps,s.notes,n||null,o,d,a);return{id:Number(m.lastInsertRowid),createdAtEpoch:a}}storeObservations(e,t,s,n,o,i=0,a){let d=a??Date.now(),c=new Date(d).toISOString();return this.db.transaction(()=>{let l=[],T=this.db.prepare(`
500
+ `).run(e,t,s.request,s.investigated,s.learned,s.completed,s.next_steps,s.notes,n||null,o,d,a);return{id:Number(_.lastInsertRowid),createdAtEpoch:a}}storeObservations(e,t,s,n,o,i=0,a,d){let u=a??Date.now(),_=new Date(u).toISOString();return this.db.transaction(()=>{let E=[],T=this.db.prepare(`
449
501
  INSERT INTO observations
450
502
  (memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
451
- files_read, files_modified, prompt_number, discovery_tokens, content_hash, created_at, created_at_epoch)
452
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
453
- `);for(let f of s){let R=w(e,f.title,f.narrative),u=$(this.db,R,d);if(u){l.push(u.id);continue}let S=T.run(e,t,f.type,f.title,f.subtitle,JSON.stringify(f.facts),f.narrative,JSON.stringify(f.concepts),JSON.stringify(f.files_read),JSON.stringify(f.files_modified),o||null,i,R,c,d);l.push(Number(S.lastInsertRowid))}let E=null;if(n){let R=this.db.prepare(`
503
+ files_read, files_modified, prompt_number, discovery_tokens, content_hash, created_at, created_at_epoch,
504
+ generated_by_model)
505
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
506
+ `);for(let S of s){let p=P(e,S.title,S.narrative),R=H(this.db,p,u);if(R){E.push(R.id);continue}let g=T.run(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),o||null,i,p,_,u,d||null);E.push(Number(g.lastInsertRowid))}let O=null;if(n){let p=this.db.prepare(`
454
507
  INSERT INTO session_summaries
455
508
  (memory_session_id, project, request, investigated, learned, completed,
456
509
  next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
457
510
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
458
- `).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,o||null,i,c,d);E=Number(R.lastInsertRowid)}return{observationIds:l,summaryId:E,createdAtEpoch:d}})()}storeObservationsAndMarkComplete(e,t,s,n,o,i,a,d=0,c){let m=c??Date.now(),l=new Date(m).toISOString();return this.db.transaction(()=>{let E=[],f=this.db.prepare(`
511
+ `).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,o||null,i,_,u);O=Number(p.lastInsertRowid)}return{observationIds:E,summaryId:O,createdAtEpoch:u}})()}storeObservationsAndMarkComplete(e,t,s,n,o,i,a,d=0,u,_){let l=u??Date.now(),E=new Date(l).toISOString();return this.db.transaction(()=>{let O=[],S=this.db.prepare(`
459
512
  INSERT INTO observations
460
513
  (memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
461
- files_read, files_modified, prompt_number, discovery_tokens, content_hash, created_at, created_at_epoch)
462
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
463
- `);for(let S of s){let g=w(e,S.title,S.narrative),h=$(this.db,g,m);if(h){E.push(h.id);continue}let Et=f.run(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),a||null,d,g,l,m);E.push(Number(Et.lastInsertRowid))}let R;if(n){let g=this.db.prepare(`
514
+ files_read, files_modified, prompt_number, discovery_tokens, content_hash, created_at, created_at_epoch,
515
+ generated_by_model)
516
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
517
+ `);for(let g of s){let b=P(e,g.title,g.narrative),_e=H(this.db,b,l);if(_e){O.push(_e.id);continue}let Ot=S.run(e,t,g.type,g.title,g.subtitle,JSON.stringify(g.facts),g.narrative,JSON.stringify(g.concepts),JSON.stringify(g.files_read),JSON.stringify(g.files_modified),a||null,d,b,E,l,_||null);O.push(Number(Ot.lastInsertRowid))}let p;if(n){let b=this.db.prepare(`
464
518
  INSERT INTO session_summaries
465
519
  (memory_session_id, project, request, investigated, learned, completed,
466
520
  next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
467
521
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
468
- `).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,a||null,d,l,m);R=Number(g.lastInsertRowid)}return this.db.prepare(`
522
+ `).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,a||null,d,E,l);p=Number(b.lastInsertRowid)}return this.db.prepare(`
469
523
  UPDATE pending_messages
470
524
  SET
471
525
  status = 'processed',
@@ -473,46 +527,46 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
473
527
  tool_input = NULL,
474
528
  tool_response = NULL
475
529
  WHERE id = ? AND status = 'processing'
476
- `).run(m,o),{observationIds:E,summaryId:R,createdAtEpoch:m}})()}getSessionSummariesByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o}=t,i=s==="date_asc"?"ASC":"DESC",a=n?`LIMIT ${n}`:"",d=e.map(()=>"?").join(","),c=[...e],m=o?`WHERE id IN (${d}) AND project = ?`:`WHERE id IN (${d})`;return o&&c.push(o),this.db.prepare(`
530
+ `).run(l,o),{observationIds:O,summaryId:p,createdAtEpoch:l}})()}getSessionSummariesByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o}=t,i=s==="date_asc"?"ASC":"DESC",a=n?`LIMIT ${n}`:"",d=e.map(()=>"?").join(","),u=[...e],_=o?`WHERE id IN (${d}) AND project = ?`:`WHERE id IN (${d})`;return o&&u.push(o),this.db.prepare(`
477
531
  SELECT * FROM session_summaries
478
- ${m}
532
+ ${_}
479
533
  ORDER BY created_at_epoch ${i}
480
534
  ${a}
481
- `).all(...c)}getUserPromptsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o}=t,i=s==="date_asc"?"ASC":"DESC",a=n?`LIMIT ${n}`:"",d=e.map(()=>"?").join(","),c=[...e],m=o?"AND s.project = ?":"";return o&&c.push(o),this.db.prepare(`
535
+ `).all(...u)}getUserPromptsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o}=t,i=s==="date_asc"?"ASC":"DESC",a=n?`LIMIT ${n}`:"",d=e.map(()=>"?").join(","),u=[...e],_=o?"AND s.project = ?":"";return o&&u.push(o),this.db.prepare(`
482
536
  SELECT
483
537
  up.*,
484
538
  s.project,
485
539
  s.memory_session_id
486
540
  FROM user_prompts up
487
541
  JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
488
- WHERE up.id IN (${d}) ${m}
542
+ WHERE up.id IN (${d}) ${_}
489
543
  ORDER BY up.created_at_epoch ${i}
490
544
  ${a}
491
- `).all(...c)}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 u=`
545
+ `).all(...u)}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,u;if(e!==null){let p=`
492
546
  SELECT id, created_at_epoch
493
547
  FROM observations
494
548
  WHERE id <= ? ${i}
495
549
  ORDER BY id DESC
496
550
  LIMIT ?
497
- `,S=`
551
+ `,R=`
498
552
  SELECT id, created_at_epoch
499
553
  FROM observations
500
554
  WHERE id >= ? ${i}
501
555
  ORDER BY id ASC
502
556
  LIMIT ?
503
- `;try{let g=this.db.prepare(u).all(e,...a,s+1),h=this.db.prepare(S).all(e,...a,n+1);if(g.length===0&&h.length===0)return{observations:[],sessions:[],prompts:[]};d=g.length>0?g[g.length-1].created_at_epoch:t,c=h.length>0?h[h.length-1].created_at_epoch:t}catch(g){return p.error("DB","Error getting boundary observations",void 0,{error:g,project:o}),{observations:[],sessions:[],prompts:[]}}}else{let u=`
557
+ `;try{let g=this.db.prepare(p).all(e,...a,s+1),b=this.db.prepare(R).all(e,...a,n+1);if(g.length===0&&b.length===0)return{observations:[],sessions:[],prompts:[]};d=g.length>0?g[g.length-1].created_at_epoch:t,u=b.length>0?b[b.length-1].created_at_epoch:t}catch(g){return m.error("DB","Error getting boundary observations",void 0,{error:g,project:o}),{observations:[],sessions:[],prompts:[]}}}else{let p=`
504
558
  SELECT created_at_epoch
505
559
  FROM observations
506
560
  WHERE created_at_epoch <= ? ${i}
507
561
  ORDER BY created_at_epoch DESC
508
562
  LIMIT ?
509
- `,S=`
563
+ `,R=`
510
564
  SELECT created_at_epoch
511
565
  FROM observations
512
566
  WHERE created_at_epoch >= ? ${i}
513
567
  ORDER BY created_at_epoch ASC
514
568
  LIMIT ?
515
- `;try{let g=this.db.prepare(u).all(t,...a,s),h=this.db.prepare(S).all(t,...a,n+1);if(g.length===0&&h.length===0)return{observations:[],sessions:[],prompts:[]};d=g.length>0?g[g.length-1].created_at_epoch:t,c=h.length>0?h[h.length-1].created_at_epoch:t}catch(g){return p.error("DB","Error getting boundary timestamps",void 0,{error:g,project:o}),{observations:[],sessions:[],prompts:[]}}}let m=`
569
+ `;try{let g=this.db.prepare(p).all(t,...a,s),b=this.db.prepare(R).all(t,...a,n+1);if(g.length===0&&b.length===0)return{observations:[],sessions:[],prompts:[]};d=g.length>0?g[g.length-1].created_at_epoch:t,u=b.length>0?b[b.length-1].created_at_epoch:t}catch(g){return m.error("DB","Error getting boundary timestamps",void 0,{error:g,project:o}),{observations:[],sessions:[],prompts:[]}}}let _=`
516
570
  SELECT *
517
571
  FROM observations
518
572
  WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${i}
@@ -522,13 +576,13 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
522
576
  FROM session_summaries
523
577
  WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${i}
524
578
  ORDER BY created_at_epoch ASC
525
- `,T=`
579
+ `,E=`
526
580
  SELECT up.*, s.project, s.memory_session_id
527
581
  FROM user_prompts up
528
582
  JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
529
583
  WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${i.replace("project","s.project")}
530
584
  ORDER BY up.created_at_epoch ASC
531
- `,E=this.db.prepare(m).all(d,c,...a),f=this.db.prepare(l).all(d,c,...a),R=this.db.prepare(T).all(d,c,...a);return{observations:E,sessions:f.map(u=>({id:u.id,memory_session_id:u.memory_session_id,project:u.project,request:u.request,completed:u.completed,next_steps:u.next_steps,created_at:u.created_at,created_at_epoch:u.created_at_epoch})),prompts:R.map(u=>({id:u.id,content_session_id:u.content_session_id,prompt_number:u.prompt_number,prompt_text:u.prompt_text,project:u.project,created_at:u.created_at,created_at_epoch:u.created_at_epoch}))}}getPromptById(e){return this.db.prepare(`
585
+ `,T=this.db.prepare(_).all(d,u,...a),O=this.db.prepare(l).all(d,u,...a),S=this.db.prepare(E).all(d,u,...a);return{observations:T,sessions:O.map(p=>({id:p.id,memory_session_id:p.memory_session_id,project:p.project,request:p.request,completed:p.completed,next_steps:p.next_steps,created_at:p.created_at,created_at_epoch:p.created_at_epoch})),prompts:S.map(p=>({id:p.id,content_session_id:p.content_session_id,prompt_number:p.prompt_number,prompt_text:p.prompt_text,project:p.project,created_at:p.created_at,created_at_epoch:p.created_at_epoch}))}}getPromptById(e){return this.db.prepare(`
532
586
  SELECT
533
587
  p.id,
534
588
  p.content_session_id,
@@ -570,14 +624,14 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
570
624
  WHERE id = ?
571
625
  LIMIT 1
572
626
  `).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(`
573
- INSERT INTO sdk_sessions (memory_session_id, content_session_id, project, started_at, started_at_epoch, status)
574
- VALUES (?, ?, ?, ?, ?, 'active')
575
- `).run(t,s,e,o.toISOString(),o.getTime()),p.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(`
627
+ INSERT INTO sdk_sessions (memory_session_id, content_session_id, project, platform_source, started_at, started_at_epoch, status)
628
+ VALUES (?, ?, ?, ?, ?, ?, 'active')
629
+ `).run(t,s,e,h,o.toISOString(),o.getTime()),m.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(`
576
630
  INSERT INTO sdk_sessions (
577
- content_session_id, memory_session_id, project, user_prompt,
631
+ content_session_id, memory_session_id, project, platform_source, user_prompt,
578
632
  started_at, started_at_epoch, completed_at, completed_at_epoch, status
579
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
580
- `).run(e.content_session_id,e.memory_session_id,e.project,e.user_prompt,e.started_at,e.started_at_epoch,e.completed_at,e.completed_at_epoch,e.status).lastInsertRowid}}importSessionSummary(e){let t=this.db.prepare("SELECT id FROM session_summaries WHERE memory_session_id = ?").get(e.memory_session_id);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(`
633
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
634
+ `).run(e.content_session_id,e.memory_session_id,e.project,y(e.platform_source),e.user_prompt,e.started_at,e.started_at_epoch,e.completed_at,e.completed_at_epoch,e.status).lastInsertRowid}}importSessionSummary(e){let t=this.db.prepare("SELECT id FROM session_summaries WHERE memory_session_id = ?").get(e.memory_session_id);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(`
581
635
  INSERT INTO session_summaries (
582
636
  memory_session_id, project, request, investigated, learned,
583
637
  completed, next_steps, files_read, files_edited, notes,
@@ -600,54 +654,106 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
600
654
  content_session_id, prompt_number, prompt_text,
601
655
  created_at, created_at_epoch
602
656
  ) VALUES (?, ?, ?, ?, ?)
603
- `).run(e.content_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var ge=M(require("path"),1);function fe(r){if(!r||r.trim()==="")return p.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=ge.default.basename(r);if(e===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let o=`drive-${s[1].toUpperCase()}`;return p.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:o}),o}}return p.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return e}var be=M(require("path"),1),he=require("os");var N=require("fs"),X=require("path"),Se=require("os"),P=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",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,X.join)((0,Se.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_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"true",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_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"};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,N.existsSync)(e)){let i=this.getAllDefaults();try{let a=(0,X.dirname)(e);(0,N.existsSync)(a)||(0,N.mkdirSync)(a,{recursive:!0}),(0,N.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)}return this.applyEnvOverrides(i)}let t=(0,N.readFileSync)(e,"utf-8"),s=JSON.parse(t),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{(0,N.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)}}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),this.applyEnvOverrides(this.getAllDefaults())}}};var y=require("fs"),j=require("path");var O=class r{static instance=null;activeMode=null;modesDir;constructor(){let e=le(),t=[(0,j.join)(e,"modes"),(0,j.join)(e,"..","plugin","modes")],s=t.find(n=>(0,y.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,j.join)(this.modesDir,`${e}.json`);if(!(0,y.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let s=(0,y.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,p.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{if(p.warn("SYSTEM",`Mode file not found: ${e}, falling back to 'code'`),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{p.warn("SYSTEM",`Parent mode '${s}' not found for ${e}, falling back to 'code'`),o=this.loadMode("code")}let i;try{i=this.loadModeFile(n),p.debug("SYSTEM",`Loaded override file: ${n} for parent ${s}`)}catch{return p.warn("SYSTEM",`Override file '${n}' not found, using parent mode '${s}' only`),this.activeMode=o,o}if(!i)return p.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,p.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 J(){let r=be.default.join((0,he.homedir)(),".claude-mem","settings.json"),e=P.loadFromFile(r),t=O.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"},Oe=4,Q=1;function z(r){let e=(r.title?.length||0)+(r.subtitle?.length||0)+(r.narrative?.length||0)+JSON.stringify(r.facts||[]).length;return Math.ceil(e/Oe)}function Z(r){let e=r.length,t=r.reduce((i,a)=>i+z(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 Mt(r){return O.getInstance().getWorkEmoji(r)}function v(r,e){let t=z(r),s=r.discovery_tokens||0,n=Mt(r.type),o=s>0?`${n} ${s.toLocaleString()}`:"-";return{readTokens:t,discoveryTokens:s,discoveryDisplay:o,workEmoji:n}}function G(r){return r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent}var Re=M(require("path"),1),H=require("fs");function ee(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(`
657
+ `).run(e.content_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var Ae=require("os"),Re=D(require("path"),1);function Ft(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,Ae.homedir)()):r}function Ne(r){if(!r||r.trim()==="")return m.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Ft(r),t=Re.default.basename(e);if(t===""){if(process.platform==="win32"){let n=r.match(/^([A-Z]):\\/i);if(n){let i=`drive-${n[1].toUpperCase()}`;return m.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:i}),i}}return m.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return t}var Ce=D(require("path"),1),Ie=require("os");var C=require("fs"),v=require("path"),Z=require("os"),j=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-6",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",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_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,v.join)((0,Z.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_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,v.join)((0,Z.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",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_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"};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,C.existsSync)(e)){let i=this.getAllDefaults();try{let a=(0,v.dirname)(e);(0,C.existsSync)(a)||(0,C.mkdirSync)(a,{recursive:!0}),(0,C.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)}return this.applyEnvOverrides(i)}let t=(0,C.readFileSync)(e,"utf-8"),s=JSON.parse(t),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{(0,C.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)}}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),this.applyEnvOverrides(this.getAllDefaults())}}};var U=require("fs"),G=require("path");var A=class r{static instance=null;activeMode=null;modesDir;constructor(){let e=Se(),t=[(0,G.join)(e,"modes"),(0,G.join)(e,"..","plugin","modes")],s=t.find(n=>(0,U.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,G.join)(this.modesDir,`${e}.json`);if(!(0,U.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let s=(0,U.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,m.debug("SYSTEM",`Loaded mode: ${d.name} (${e})`,void 0,{types:d.observation_types.map(u=>u.id),concepts:d.observation_concepts.map(u=>u.id)}),d}catch{if(m.warn("SYSTEM",`Mode file not found: ${e}, falling back to 'code'`),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{m.warn("SYSTEM",`Parent mode '${s}' not found for ${e}, falling back to 'code'`),o=this.loadMode("code")}let i;try{i=this.loadModeFile(n),m.debug("SYSTEM",`Loaded override file: ${n} for parent ${s}`)}catch{return m.warn("SYSTEM",`Override file '${n}' not found, using parent mode '${s}' only`),this.activeMode=o,o}if(!i)return m.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,m.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 ee(){let r=Ce.default.join((0,Ie.homedir)(),".claude-mem","settings.json"),e=j.loadFromFile(r),t=A.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 c={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"},Le=4,te=1;function se(r){let e=(r.title?.length||0)+(r.subtitle?.length||0)+(r.narrative?.length||0)+JSON.stringify(r.facts||[]).length;return Math.ceil(e/Le)}function re(r){let e=r.length,t=r.reduce((i,a)=>i+se(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 wt(r){return A.getInstance().getWorkEmoji(r)}function x(r,e){let t=se(r),s=r.discovery_tokens||0,n=wt(r.type),o=s>0?`${n} ${s.toLocaleString()}`:"-";return{readTokens:t,discoveryTokens:s,discoveryDisplay:o,workEmoji:n}}function B(r){return r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent}var De=D(require("path"),1),W=require("fs");var ye=/<system-reminder>[\s\S]*?<\/system-reminder>/g;function ne(r,e,t,s){let n=Array.from(t.observationTypes),o=n.map(()=>"?").join(","),i=Array.from(t.observationConcepts),a=i.map(()=>"?").join(",");return r.db.prepare(`
604
658
  SELECT
605
- id, memory_session_id, type, title, subtitle, narrative,
606
- facts, concepts, files_read, files_modified, discovery_tokens,
607
- created_at, created_at_epoch
608
- FROM observations
609
- WHERE project = ?
610
- AND type IN (${n})
659
+ o.id,
660
+ o.memory_session_id,
661
+ COALESCE(s.platform_source, 'claude') as platform_source,
662
+ o.type,
663
+ o.title,
664
+ o.subtitle,
665
+ o.narrative,
666
+ o.facts,
667
+ o.concepts,
668
+ o.files_read,
669
+ o.files_modified,
670
+ o.discovery_tokens,
671
+ o.created_at,
672
+ o.created_at_epoch
673
+ FROM observations o
674
+ LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
675
+ WHERE o.project = ?
676
+ AND type IN (${o})
611
677
  AND EXISTS (
612
- SELECT 1 FROM json_each(concepts)
613
- WHERE value IN (${i})
678
+ SELECT 1 FROM json_each(o.concepts)
679
+ WHERE value IN (${a})
614
680
  )
615
- ORDER BY created_at_epoch DESC
681
+ ${s?"AND COALESCE(s.platform_source, 'claude') = ?":""}
682
+ ORDER BY o.created_at_epoch DESC
616
683
  LIMIT ?
617
- `).all(e,...s,...o,t.totalObservationCount)}function te(r,e,t){return r.db.prepare(`
618
- SELECT id, memory_session_id, request, investigated, learned, completed, next_steps, created_at, created_at_epoch
619
- FROM session_summaries
620
- WHERE project = ?
621
- ORDER BY created_at_epoch DESC
684
+ `).all(e,...n,...i,...s?[s]:[],t.totalObservationCount)}function oe(r,e,t,s){return r.db.prepare(`
685
+ SELECT
686
+ ss.id,
687
+ ss.memory_session_id,
688
+ COALESCE(s.platform_source, 'claude') as platform_source,
689
+ ss.request,
690
+ ss.investigated,
691
+ ss.learned,
692
+ ss.completed,
693
+ ss.next_steps,
694
+ ss.created_at,
695
+ ss.created_at_epoch
696
+ FROM session_summaries ss
697
+ LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
698
+ WHERE ss.project = ?
699
+ ${s?"AND COALESCE(s.platform_source, 'claude') = ?":""}
700
+ ORDER BY ss.created_at_epoch DESC
622
701
  LIMIT ?
623
- `).all(e,t.sessionCount+Q)}function Ce(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(`
702
+ `).all(e,...s?[s]:[],t.sessionCount+te)}function Me(r,e,t,s){let n=Array.from(t.observationTypes),o=n.map(()=>"?").join(","),i=Array.from(t.observationConcepts),a=i.map(()=>"?").join(","),d=e.map(()=>"?").join(",");return r.db.prepare(`
624
703
  SELECT
625
- id, memory_session_id, type, title, subtitle, narrative,
626
- facts, concepts, files_read, files_modified, discovery_tokens,
627
- created_at, created_at_epoch, project
628
- FROM observations
629
- WHERE project IN (${a})
630
- AND type IN (${n})
704
+ o.id,
705
+ o.memory_session_id,
706
+ COALESCE(s.platform_source, 'claude') as platform_source,
707
+ o.type,
708
+ o.title,
709
+ o.subtitle,
710
+ o.narrative,
711
+ o.facts,
712
+ o.concepts,
713
+ o.files_read,
714
+ o.files_modified,
715
+ o.discovery_tokens,
716
+ o.created_at,
717
+ o.created_at_epoch,
718
+ o.project
719
+ FROM observations o
720
+ LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
721
+ WHERE o.project IN (${d})
722
+ AND type IN (${o})
631
723
  AND EXISTS (
632
- SELECT 1 FROM json_each(concepts)
633
- WHERE value IN (${i})
724
+ SELECT 1 FROM json_each(o.concepts)
725
+ WHERE value IN (${a})
634
726
  )
635
- ORDER BY created_at_epoch DESC
727
+ ${s?"AND COALESCE(s.platform_source, 'claude') = ?":""}
728
+ ORDER BY o.created_at_epoch DESC
636
729
  LIMIT ?
637
- `).all(...e,...s,...o,t.totalObservationCount)}function Ne(r,e,t){let s=e.map(()=>"?").join(",");return r.db.prepare(`
638
- SELECT id, memory_session_id, request, investigated, learned, completed, next_steps, created_at, created_at_epoch, project
639
- FROM session_summaries
640
- WHERE project IN (${s})
641
- ORDER BY created_at_epoch DESC
730
+ `).all(...e,...n,...i,...s?[s]:[],t.totalObservationCount)}function ve(r,e,t,s){let n=e.map(()=>"?").join(",");return r.db.prepare(`
731
+ SELECT
732
+ ss.id,
733
+ ss.memory_session_id,
734
+ COALESCE(s.platform_source, 'claude') as platform_source,
735
+ ss.request,
736
+ ss.investigated,
737
+ ss.learned,
738
+ ss.completed,
739
+ ss.next_steps,
740
+ ss.created_at,
741
+ ss.created_at_epoch,
742
+ ss.project
743
+ FROM session_summaries ss
744
+ LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
745
+ WHERE ss.project IN (${n})
746
+ ${s?"AND COALESCE(s.platform_source, 'claude') = ?":""}
747
+ ORDER BY ss.created_at_epoch DESC
642
748
  LIMIT ?
643
- `).all(...e,t.sessionCount+Q)}function Lt(r){return r.replace(/\//g,"-")}function yt(r){try{if(!(0,H.existsSync)(r))return{userMessage:"",assistantMessage:""};let e=(0,H.readFileSync)(r,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(`
644
- `).filter(n=>n.trim()),s="";for(let n=t.length-1;n>=0;n--)try{let o=t[n];if(!o.includes('"type":"assistant"'))continue;let i=JSON.parse(o);if(i.type==="assistant"&&i.message?.content&&Array.isArray(i.message.content)){let a="";for(let d of i.message.content)d.type==="text"&&(a+=d.text);if(a=a.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"").trim(),a){s=a;break}}}catch(o){p.debug("PARSER","Skipping malformed transcript line",{lineIndex:n},o);continue}return{userMessage:"",assistantMessage:s}}catch(e){return p.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e),{userMessage:"",assistantMessage:""}}}function se(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=Lt(s),a=Re.default.join(A,"projects",i,`${o}.jsonl`);return yt(a)}function Ie(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 re(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 Ae(r,e){return new Set(r.slice(0,e).map(t=>t.id))}function Me(){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 Le(r){return[`# $CMEM ${r} ${Me()}`,""]}function ye(){return[`Legend: \u{1F3AF}session ${O.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 ve(){return[]}function De(){return[]}function Ue(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 xe(r){return[`### ${r}`]}function ke(r){return r.toLowerCase().replace(" am","a").replace(" pm","p")}function we(r,e,t){let s=r.title||"Untitled",n=O.getInstance().getTypeIcon(r.type),o=e?ke(e):'"';return`${r.id} ${o} ${n} ${s}`}function $e(r,e,t,s){let n=[],o=r.title||"Untitled",i=O.getInstance().getTypeIcon(r.type),a=e?ke(e):'"',{readTokens:d,discoveryDisplay:c}=v(r,s);n.push(`**${r.id}** ${a} ${i} **${o}**`),t&&n.push(t);let m=[];return s.showReadTokens&&m.push(`~${d}t`),s.showWorkTokens&&m.push(c),m.length>0&&n.push(m.join(" ")),n.push(""),n}function Fe(r,e){return[`S${r.id} ${r.request||"Session started"} (${e})`]}function D(r,e){return e?[`**${r}**: ${e}`,""]:[]}function Pe(r){return r.assistantMessage?["","---","","**Previously**","",`A: ${r.assistantMessage}`,""]:[]}function Xe(r,e){return["",`Access ${Math.round(r/1e3)}k tokens of past work via get_observations([IDs]) or mem-search skill.`]}function je(r){return`# $CMEM ${r} ${Me()}
749
+ `).all(...e,...s?[s]:[],t.sessionCount+te)}function Pt(r){return r.replace(/\//g,"-")}function Ht(r){try{if(!(0,W.existsSync)(r))return{userMessage:"",assistantMessage:""};let e=(0,W.readFileSync)(r,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(`
750
+ `).filter(n=>n.trim()),s="";for(let n=t.length-1;n>=0;n--)try{let o=t[n];if(!o.includes('"type":"assistant"'))continue;let i=JSON.parse(o);if(i.type==="assistant"&&i.message?.content&&Array.isArray(i.message.content)){let a="";for(let d of i.message.content)d.type==="text"&&(a+=d.text);if(a=a.replace(ye,"").trim(),a){s=a;break}}}catch(o){m.debug("PARSER","Skipping malformed transcript line",{lineIndex:n},o);continue}return{userMessage:"",assistantMessage:s}}catch(e){return m.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e),{userMessage:"",assistantMessage:""}}}function ie(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=Pt(s),a=De.default.join(L,"projects",i,`${o}.jsonl`);return Ht(a)}function Ue(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 ae(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 xe(r,e){return new Set(r.slice(0,e).map(t=>t.id))}function ke(){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 $e(r){return[`# $CMEM ${r} ${ke()}`,""]}function Fe(){return[`Legend: \u{1F3AF}session ${A.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 we(){return[]}function Pe(){return[]}function He(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 Xe(r){return[`### ${r}`]}function je(r){return r.toLowerCase().replace(" am","a").replace(" pm","p")}function Ge(r,e,t){let s=r.title||"Untitled",n=A.getInstance().getTypeIcon(r.type),o=e?je(e):'"';return`${r.id} ${o} ${n} ${s}`}function Be(r,e,t,s){let n=[],o=r.title||"Untitled",i=A.getInstance().getTypeIcon(r.type),a=e?je(e):'"',{readTokens:d,discoveryDisplay:u}=x(r,s);n.push(`**${r.id}** ${a} ${i} **${o}**`),t&&n.push(t);let _=[];return s.showReadTokens&&_.push(`~${d}t`),s.showWorkTokens&&_.push(u),_.length>0&&n.push(_.join(" ")),n.push(""),n}function We(r,e){return[`S${r.id} ${r.request||"Session started"} (${e})`]}function k(r,e){return e?[`**${r}**: ${e}`,""]:[]}function Ye(r){return r.assistantMessage?["","---","","**Previously**","",`A: ${r.assistantMessage}`,""]:[]}function qe(r,e){return["",`Access ${Math.round(r/1e3)}k tokens of past work via get_observations([IDs]) or mem-search skill.`]}function Ve(r){return`# $CMEM ${r} ${ke()}
645
751
 
646
- No previous sessions found.`}function Ge(){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 He(r){return["",`${_.bright}${_.cyan}[${r}] recent context, ${Ge()}${_.reset}`,`${_.gray}${"\u2500".repeat(60)}${_.reset}`,""]}function Be(){let e=O.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ");return[`${_.dim}Legend: session-request | ${e}${_.reset}`,""]}function We(){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 Ye(){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 qe(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 Ve(r){return[`${_.bright}${_.cyan}${r}${_.reset}`,""]}function Ke(r){return[`${_.dim}${r}${_.reset}`]}function Je(r,e,t,s){let n=r.title||"Untitled",o=O.getInstance().getTypeIcon(r.type),{readTokens:i,discoveryTokens:a,workEmoji:d}=v(r,s),c=t?`${_.dim}${e}${_.reset}`:" ".repeat(e.length),m=s.showReadTokens&&i>0?`${_.dim}(~${i}t)${_.reset}`:"",l=s.showWorkTokens&&a>0?`${_.dim}(${d} ${a.toLocaleString()}t)${_.reset}`:"";return` ${_.dim}#${r.id}${_.reset} ${c} ${o} ${n} ${m} ${l}`}function Qe(r,e,t,s,n){let o=[],i=r.title||"Untitled",a=O.getInstance().getTypeIcon(r.type),{readTokens:d,discoveryTokens:c,workEmoji:m}=v(r,n),l=t?`${_.dim}${e}${_.reset}`:" ".repeat(e.length),T=n.showReadTokens&&d>0?`${_.dim}(~${d}t)${_.reset}`:"",E=n.showWorkTokens&&c>0?`${_.dim}(${m} ${c.toLocaleString()}t)${_.reset}`:"";return o.push(` ${_.dim}#${r.id}${_.reset} ${l} ${a} ${_.bright}${i}${_.reset}`),s&&o.push(` ${_.dim}${s}${_.reset}`),(T||E)&&o.push(` ${T} ${E}`),o.push(""),o}function ze(r,e){let t=`${r.request||"Session started"} (${e})`;return[`${_.yellow}#S${r.id}${_.reset} ${t}`,""]}function U(r,e,t){return e?[`${t}${r}:${_.reset} ${e}`,""]:[]}function Ze(r){return r.assistantMessage?["","---","",`${_.bright}${_.magenta}Previously${_.reset}`,"",`${_.dim}A: ${r.assistantMessage}${_.reset}`,""]:[]}function et(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 tt(r){return`
647
- ${_.bright}${_.cyan}[${r}] recent context, ${Ge()}${_.reset}
648
- ${_.gray}${"\u2500".repeat(60)}${_.reset}
752
+ No previous sessions found.`}function Ke(){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 Je(r){return["",`${c.bright}${c.cyan}[${r}] recent context, ${Ke()}${c.reset}`,`${c.gray}${"\u2500".repeat(60)}${c.reset}`,""]}function ze(){let e=A.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ");return[`${c.dim}Legend: session-request | ${e}${c.reset}`,""]}function Qe(){return[`${c.bright}Column Key${c.reset}`,`${c.dim} Read: Tokens to read this observation (cost to learn it now)${c.reset}`,`${c.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${c.reset}`,""]}function Ze(){return[`${c.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${c.reset}`,"",`${c.dim}When you need implementation details, rationale, or debugging context:${c.reset}`,`${c.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${c.reset}`,`${c.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${c.reset}`,`${c.dim} - Trust this index over re-reading code for past decisions and learnings${c.reset}`,""]}function et(r,e){let t=[];if(t.push(`${c.bright}${c.cyan}Context Economics${c.reset}`),t.push(`${c.dim} Loading: ${r.totalObservations} observations (${r.totalReadTokens.toLocaleString()} tokens to read)${c.reset}`),t.push(`${c.dim} Work investment: ${r.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${c.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(`${c.green}${s}${c.reset}`)}return t.push(""),t}function tt(r){return[`${c.bright}${c.cyan}${r}${c.reset}`,""]}function st(r){return[`${c.dim}${r}${c.reset}`]}function rt(r,e,t,s){let n=r.title||"Untitled",o=A.getInstance().getTypeIcon(r.type),{readTokens:i,discoveryTokens:a,workEmoji:d}=x(r,s),u=t?`${c.dim}${e}${c.reset}`:" ".repeat(e.length),_=s.showReadTokens&&i>0?`${c.dim}(~${i}t)${c.reset}`:"",l=s.showWorkTokens&&a>0?`${c.dim}(${d} ${a.toLocaleString()}t)${c.reset}`:"";return` ${c.dim}#${r.id}${c.reset} ${u} ${o} ${n} ${_} ${l}`}function nt(r,e,t,s,n){let o=[],i=r.title||"Untitled",a=A.getInstance().getTypeIcon(r.type),{readTokens:d,discoveryTokens:u,workEmoji:_}=x(r,n),l=t?`${c.dim}${e}${c.reset}`:" ".repeat(e.length),E=n.showReadTokens&&d>0?`${c.dim}(~${d}t)${c.reset}`:"",T=n.showWorkTokens&&u>0?`${c.dim}(${_} ${u.toLocaleString()}t)${c.reset}`:"";return o.push(` ${c.dim}#${r.id}${c.reset} ${l} ${a} ${c.bright}${i}${c.reset}`),s&&o.push(` ${c.dim}${s}${c.reset}`),(E||T)&&o.push(` ${E} ${T}`),o.push(""),o}function ot(r,e){let t=`${r.request||"Session started"} (${e})`;return[`${c.yellow}#S${r.id}${c.reset} ${t}`,""]}function $(r,e,t){return e?[`${t}${r}:${c.reset} ${e}`,""]:[]}function it(r){return r.assistantMessage?["","---","",`${c.bright}${c.magenta}Previously${c.reset}`,"",`${c.dim}A: ${r.assistantMessage}${c.reset}`,""]:[]}function at(r,e){let t=Math.round(r/1e3);return["",`${c.dim}Access ${t}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use the claude-mem skill to access memories by ID.${c.reset}`]}function dt(r){return`
753
+ ${c.bright}${c.cyan}[${r}] recent context, ${Ke()}${c.reset}
754
+ ${c.gray}${"\u2500".repeat(60)}${c.reset}
649
755
 
650
- ${_.dim}No previous sessions found for this project yet.${_.reset}
651
- `}function st(r,e,t,s){let n=[];return s?n.push(...He(r)):n.push(...Le(r)),s?n.push(...Be()):n.push(...ye()),s?n.push(...We()):n.push(...ve()),s?n.push(...Ye()):n.push(...De()),G(t)&&(s?n.push(...qe(e,t)):n.push(...Ue(e,t))),n}var ne=M(require("path"),1);function Y(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return p.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e),[]}}function oe(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function ie(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function nt(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function rt(r,e){return ne.default.isAbsolute(r)?ne.default.relative(e,r):r}function ot(r,e,t){let s=Y(r);if(s.length>0)return rt(s[0],e);if(t){let n=Y(t);if(n.length>0)return rt(n[0],e)}return"General"}function vt(r){let e=new Map;for(let s of r){let n=s.type==="observation"?s.data.created_at:s.data.displayTime,o=nt(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 it(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?Y(r.facts).join(`
652
- `):null}function Dt(r,e,t,s){let n=[];n.push(...xe(r));let o="";for(let i of e)if(i.type==="summary"){o="";let a=i.data,d=oe(a.displayTime);n.push(...Fe(a,d))}else{let a=i.data,d=ie(a.created_at),m=d!==o?d:"";if(o=d,t.has(a.id)){let T=it(a,s);n.push(...$e(a,m,T,s))}else n.push(we(a,m,s))}return n}function Ut(r,e,t,s,n){let o=[];o.push(...Ve(r));let i=null,a="";for(let d of e)if(d.type==="summary"){i=null,a="";let c=d.data,m=oe(c.displayTime);o.push(...ze(c,m))}else{let c=d.data,m=ot(c.files_modified,n,c.files_read),l=ie(c.created_at),T=l!==a;a=l;let E=t.has(c.id);if(m!==i&&(o.push(...Ke(m)),i=m),E){let f=it(c,s);o.push(...Qe(c,l,T,f,s))}else o.push(Je(c,l,T,s))}return o.push(""),o}function xt(r,e,t,s,n,o){return o?Ut(r,e,t,s,n):Dt(r,e,t,s)}function at(r,e,t,s,n){let o=[],i=vt(r);for(let[a,d]of i)o.push(...xt(a,d,e,t,s,n));return o}function dt(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 _t(r,e){let t=[];return e?(t.push(...U("Investigated",r.investigated,_.blue)),t.push(...U("Learned",r.learned,_.yellow)),t.push(...U("Completed",r.completed,_.green)),t.push(...U("Next Steps",r.next_steps,_.magenta))):(t.push(...D("Investigated",r.investigated)),t.push(...D("Learned",r.learned)),t.push(...D("Completed",r.completed)),t.push(...D("Next Steps",r.next_steps))),t}function ct(r,e){return e?Ze(r):Pe(r)}function pt(r,e,t){return!G(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?et(r.totalDiscoveryTokens,r.totalReadTokens):Xe(r.totalDiscoveryTokens,r.totalReadTokens)}var kt=mt.default.join((0,ut.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function wt(){try{return new F}catch(r){if(r.code==="ERR_DLOPEN_FAILED"){try{(0,lt.unlinkSync)(kt)}catch(e){p.debug("SYSTEM","Marker file cleanup failed (may not exist)",{},e)}return p.error("SYSTEM","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function $t(r,e){return e?tt(r):je(r)}function Ft(r,e,t,s,n,o,i){let a=[],d=Z(e);a.push(...st(r,d,s,i));let c=t.slice(0,s.sessionCount),m=Ie(c,t),l=re(e,m),T=Ae(e,s.fullObservationCount);a.push(...at(l,T,s,n,i));let E=t[0],f=e[0];dt(s,E,f)&&a.push(..._t(E,i));let R=se(e,s,o,n);return a.push(...ct(R,i)),a.push(...pt(d,s,i)),a.join(`
653
- `).trimEnd()}async function ae(r,e=!1){let t=J(),s=r?.cwd??process.cwd(),n=fe(s),o=r?.projects||[n];r?.full&&(t.totalObservationCount=999999,t.sessionCount=999999);let i=wt();if(!i)return"";try{let a=o.length>1?Ce(i,o,t):ee(i,n,t),d=o.length>1?Ne(i,o,t):te(i,n,t);return a.length===0&&d.length===0?$t(n,e):Ft(n,a,d,t,s,r?.session_id,e)}finally{i.close()}}0&&(module.exports={generateContext});
756
+ ${c.dim}No previous sessions found for this project yet.${c.reset}
757
+ `}function ct(r,e,t,s){let n=[];return s?n.push(...Je(r)):n.push(...$e(r)),s?n.push(...ze()):n.push(...Fe()),s?n.push(...Qe()):n.push(...we()),s?n.push(...Ze()):n.push(...Pe()),B(t)&&(s?n.push(...et(e,t)):n.push(...He(e,t))),n}var de=D(require("path"),1);function V(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return m.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e),[]}}function ce(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function ue(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function mt(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function ut(r,e){return de.default.isAbsolute(r)?de.default.relative(e,r):r}function _t(r,e,t){let s=V(r);if(s.length>0)return ut(s[0],e);if(t){let n=V(t);if(n.length>0)return ut(n[0],e)}return"General"}function Xt(r){let e=new Map;for(let s of r){let n=s.type==="observation"?s.data.created_at:s.data.displayTime,o=mt(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 pt(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?V(r.facts).join(`
758
+ `):null}function jt(r,e,t,s){let n=[];n.push(...Xe(r));let o="";for(let i of e)if(i.type==="summary"){let a=i.data,d=ce(a.displayTime);n.push(...We(a,d))}else{let a=i.data,d=ue(a.created_at),_=d!==o?d:"";if(o=d,t.has(a.id)){let E=pt(a,s);n.push(...Be(a,_,E,s))}else n.push(Ge(a,_,s))}return n}function Gt(r,e,t,s,n){let o=[];o.push(...tt(r));let i=null,a="";for(let d of e)if(d.type==="summary"){i=null,a="";let u=d.data,_=ce(u.displayTime);o.push(...ot(u,_))}else{let u=d.data,_=_t(u.files_modified,n,u.files_read),l=ue(u.created_at),E=l!==a;a=l;let T=t.has(u.id);if(_!==i&&(o.push(...st(_)),i=_),T){let O=pt(u,s);o.push(...nt(u,l,E,O,s))}else o.push(rt(u,l,E,s))}return o.push(""),o}function Bt(r,e,t,s,n,o){return o?Gt(r,e,t,s,n):jt(r,e,t,s)}function lt(r,e,t,s,n){let o=[],i=Xt(r);for(let[a,d]of i)o.push(...Bt(a,d,e,t,s,n));return o}function Et(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 gt(r,e){let t=[];return e?(t.push(...$("Investigated",r.investigated,c.blue)),t.push(...$("Learned",r.learned,c.yellow)),t.push(...$("Completed",r.completed,c.green)),t.push(...$("Next Steps",r.next_steps,c.magenta))):(t.push(...k("Investigated",r.investigated)),t.push(...k("Learned",r.learned)),t.push(...k("Completed",r.completed)),t.push(...k("Next Steps",r.next_steps))),t}function Tt(r,e){return e?it(r):Ye(r)}function ft(r,e,t){return!B(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?at(r.totalDiscoveryTokens,r.totalReadTokens):qe(r.totalDiscoveryTokens,r.totalReadTokens)}var Wt=St.default.join((0,bt.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function Yt(){try{return new X}catch(r){if(r.code==="ERR_DLOPEN_FAILED"){try{(0,ht.unlinkSync)(Wt)}catch(e){m.debug("SYSTEM","Marker file cleanup failed (may not exist)",{},e)}return m.error("SYSTEM","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function qt(r,e){return e?dt(r):Ve(r)}function Vt(r,e,t,s,n,o,i){let a=[],d=re(e);a.push(...ct(r,d,s,i));let u=t.slice(0,s.sessionCount),_=Ue(u,t),l=ae(e,_),E=xe(e,s.fullObservationCount);a.push(...lt(l,E,s,n,i));let T=t[0],O=e[0];Et(s,T,O)&&a.push(...gt(T,i));let S=ie(e,s,o,n);return a.push(...Tt(S,i)),a.push(...ft(d,s,i)),a.join(`
759
+ `).trimEnd()}async function me(r,e=!1){let t=ee(),s=r?.cwd??process.cwd(),n=Ne(s),o=r?.platform_source,i=r?.projects||[n];r?.full&&(t.totalObservationCount=999999,t.sessionCount=999999);let a=Yt();if(!a)return"";try{let d=i.length>1?Me(a,i,t,o):ne(a,n,t,o),u=i.length>1?ve(a,i,t,o):oe(a,n,t,o);return d.length===0&&u.length===0?qt(n,e):Vt(n,d,u,t,s,r?.session_id,e)}finally{a.close()}}0&&(module.exports={generateContext});