@bjlee2024/claude-mem 13.4.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.
Files changed (101) hide show
  1. package/.agents/plugins/marketplace.json +20 -0
  2. package/.codex-plugin/plugin.json +46 -0
  3. package/LICENSE +202 -0
  4. package/README.md +419 -0
  5. package/dist/npx-cli/index.js +10001 -0
  6. package/dist/opencode-plugin/index.js +67 -0
  7. package/openclaw/Dockerfile.e2e +46 -0
  8. package/openclaw/SKILL.md +462 -0
  9. package/openclaw/TESTING.md +279 -0
  10. package/openclaw/dist/index.js +15 -0
  11. package/openclaw/e2e-verify.sh +222 -0
  12. package/openclaw/install.sh +1653 -0
  13. package/openclaw/openclaw.plugin.json +98 -0
  14. package/openclaw/package.json +21 -0
  15. package/openclaw/src/index.test.ts +1124 -0
  16. package/openclaw/src/index.ts +1092 -0
  17. package/openclaw/test-e2e.sh +40 -0
  18. package/openclaw/test-install.sh +2086 -0
  19. package/openclaw/test-sse-consumer.js +98 -0
  20. package/openclaw/tsconfig.json +26 -0
  21. package/package.json +211 -0
  22. package/plugin/.claude-plugin/plugin.json +24 -0
  23. package/plugin/.codex-plugin/plugin.json +46 -0
  24. package/plugin/.mcp.json +12 -0
  25. package/plugin/hooks/bugfixes-2026-01-10.md +92 -0
  26. package/plugin/hooks/codex-hooks.json +74 -0
  27. package/plugin/hooks/hooks.json +87 -0
  28. package/plugin/modes/code--ar.json +24 -0
  29. package/plugin/modes/code--bn.json +24 -0
  30. package/plugin/modes/code--chill.json +8 -0
  31. package/plugin/modes/code--cs.json +24 -0
  32. package/plugin/modes/code--da.json +24 -0
  33. package/plugin/modes/code--de.json +24 -0
  34. package/plugin/modes/code--el.json +24 -0
  35. package/plugin/modes/code--es.json +24 -0
  36. package/plugin/modes/code--fi.json +24 -0
  37. package/plugin/modes/code--fr.json +24 -0
  38. package/plugin/modes/code--he.json +24 -0
  39. package/plugin/modes/code--hi.json +24 -0
  40. package/plugin/modes/code--hu.json +24 -0
  41. package/plugin/modes/code--id.json +24 -0
  42. package/plugin/modes/code--it.json +24 -0
  43. package/plugin/modes/code--ja.json +24 -0
  44. package/plugin/modes/code--ko.json +24 -0
  45. package/plugin/modes/code--nl.json +24 -0
  46. package/plugin/modes/code--no.json +24 -0
  47. package/plugin/modes/code--pl.json +24 -0
  48. package/plugin/modes/code--pt-br.json +24 -0
  49. package/plugin/modes/code--ro.json +24 -0
  50. package/plugin/modes/code--ru.json +24 -0
  51. package/plugin/modes/code--sv.json +24 -0
  52. package/plugin/modes/code--th.json +24 -0
  53. package/plugin/modes/code--tr.json +24 -0
  54. package/plugin/modes/code--uk.json +24 -0
  55. package/plugin/modes/code--ur.json +25 -0
  56. package/plugin/modes/code--vi.json +24 -0
  57. package/plugin/modes/code--zh.json +24 -0
  58. package/plugin/modes/code.json +139 -0
  59. package/plugin/modes/email-investigation.json +120 -0
  60. package/plugin/modes/law-study--chill.json +7 -0
  61. package/plugin/modes/law-study-CLAUDE.md +85 -0
  62. package/plugin/modes/law-study.json +120 -0
  63. package/plugin/modes/meme-tokens.json +125 -0
  64. package/plugin/package.json +46 -0
  65. package/plugin/scripts/bun-runner.js +216 -0
  66. package/plugin/scripts/context-generator.cjs +795 -0
  67. package/plugin/scripts/mcp-server.cjs +239 -0
  68. package/plugin/scripts/server-beta-service.cjs +9856 -0
  69. package/plugin/scripts/statusline-counts.js +40 -0
  70. package/plugin/scripts/version-check.js +69 -0
  71. package/plugin/scripts/worker-cli.js +19 -0
  72. package/plugin/scripts/worker-service.cjs +2368 -0
  73. package/plugin/scripts/worker-wrapper.cjs +2 -0
  74. package/plugin/skills/babysit/SKILL.md +87 -0
  75. package/plugin/skills/design-is/SKILL.md +312 -0
  76. package/plugin/skills/do/SKILL.md +45 -0
  77. package/plugin/skills/how-it-works/SKILL.md +22 -0
  78. package/plugin/skills/how-it-works/onboarding-explainer.md +17 -0
  79. package/plugin/skills/knowledge-agent/SKILL.md +80 -0
  80. package/plugin/skills/learn-codebase/SKILL.md +21 -0
  81. package/plugin/skills/make-plan/SKILL.md +67 -0
  82. package/plugin/skills/mem-search/SKILL.md +131 -0
  83. package/plugin/skills/oh-my-issues/SKILL.md +226 -0
  84. package/plugin/skills/pathfinder/SKILL.md +111 -0
  85. package/plugin/skills/smart-explore/SKILL.md +190 -0
  86. package/plugin/skills/timeline-report/SKILL.md +211 -0
  87. package/plugin/skills/version-bump/SKILL.md +68 -0
  88. package/plugin/skills/version-bump/scripts/generate_changelog.js +34 -0
  89. package/plugin/skills/weekly-digests/SKILL.md +262 -0
  90. package/plugin/skills/wowerpoint/SKILL.md +205 -0
  91. package/plugin/ui/assets/fonts/monaspace-radon-var.woff +0 -0
  92. package/plugin/ui/assets/fonts/monaspace-radon-var.woff2 +0 -0
  93. package/plugin/ui/claude-mem-logo-for-dark-mode.webp +0 -0
  94. package/plugin/ui/claude-mem-logo-stylized.png +0 -0
  95. package/plugin/ui/claude-mem-logomark.webp +0 -0
  96. package/plugin/ui/icon-thick-completed.svg +8 -0
  97. package/plugin/ui/icon-thick-investigated.svg +8 -0
  98. package/plugin/ui/icon-thick-learned.svg +12 -0
  99. package/plugin/ui/icon-thick-next-steps.svg +8 -0
  100. package/plugin/ui/viewer-bundle.js +65 -0
  101. package/plugin/ui/viewer.html +3145 -0
@@ -0,0 +1,795 @@
1
+ "use strict";var vt=Object.create;var G=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,wt=Object.prototype.hasOwnProperty;var kt=(r,e)=>{for(var t in e)G(r,t,{get:e[t],enumerable:!0})},Oe=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ut(e))!wt.call(r,n)&&n!==t&&G(r,n,{get:()=>e[n],enumerable:!(s=yt(e,n))||s.enumerable});return r};var U=(r,e,t)=>(t=r!=null?vt(xt(r)):{},Oe(e||!r||!r.__esModule?G(t,"default",{value:r,enumerable:!0}):t,r)),Ft=r=>Oe(G({},"__esModule",{value:!0}),r);var ps={};kt(ps,{generateContext:()=>Se});module.exports=Ft(ps);var Lt=U(require("path"),1),Mt=require("os"),Dt=require("fs");var ie=require("bun:sqlite");var g=require("path"),se=require("os"),D=require("fs");var Ae=require("url");var L=require("fs"),Re=require("path");var $t=null;function Pt(r){return($t??process.stderr.write.bind(process.stderr))(r)}function Z(r){Pt(r)}var ee=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(ee||{}),te=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=x.logsDir();(0,L.existsSync)(e)||(0,L.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,Re.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=x.settings();if((0,L.existsSync)(e)){let t=(0,L.readFileSync)(e,"utf-8"),n=(JSON.parse(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=ee[n]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}correlationId(e,t){return`obs-${e}-${t}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
2
+ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let s=t;if(typeof t=="string")try{s=JSON.parse(t)}catch{s=t}if(e==="Bash"&&s.command)return`${e}(${s.command})`;if(s.file_path)return`${e}(${s.file_path})`;if(s.notebook_path)return`${e}(${s.notebook_path})`;if(e==="Glob"&&s.pattern)return`${e}(${s.pattern})`;if(e==="Grep"&&s.pattern)return`${e}(${s.pattern})`;if(s.url)return`${e}(${s.url})`;if(s.query)return`${e}(${s.query})`;if(e==="Task"){if(s.subagent_type)return`${e}(${s.subagent_type})`;if(s.description)return`${e}(${s.description})`}return e==="Skill"&&s.skill?`${e}(${s.skill})`:e==="LSP"&&s.operation?`${e}(${s.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),d=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${s}-${n} ${o}:${i}:${a}.${d}`}log(e,t,s,n,o){if(e<this.getLevel())return;this.ensureLogFileInitialized();let i=this.formatTimestamp(new Date),a=ee[e].padEnd(5),d=t.padEnd(6),l="";n?.correlationId?l=`[${n.correlationId}] `:n?.sessionId&&(l=`[session-${n.sessionId}] `);let c="";if(o!=null)if(o instanceof Error)c=this.getLevel()===0?`
3
+ ${o.message}
4
+ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{c=`
5
+ `+JSON.stringify(o,null,2)}catch{c=" "+this.formatData(o)}else c=" "+this.formatData(o);let T="";if(n){let{sessionId:E,memorySessionId:f,correlationId:b,...m}=n;Object.keys(m).length>0&&(T=` {${Object.entries(m).map(([h,S])=>`${h}=${S}`).join(", ")}}`)}let p=`[${i}] [${a}] [${d}] ${l}${s}${T}${c}`;if(this.logFilePath)try{(0,L.appendFileSync)(this.logFilePath,p+`
6
+ `,"utf8")}catch(E){Z(`[LOGGER] Failed to write to log file: ${E instanceof Error?E.message:String(E)}
7
+ `)}else Z(p+`
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 l=((new Error().stack||"").split(`
9
+ `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),c=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",T={...s,location:c};return this.warn(e,`[HAPPY-PATH] ${t}`,T,n),o}},u=new te;var Kt={};function Ht(){return typeof __dirname<"u"?__dirname:(0,g.dirname)((0,Ae.fileURLToPath)(Kt.url))}var Gt=Ht();function jt(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let r=(0,g.join)((0,se.homedir)(),".claude-mem"),e=(0,g.join)(r,"settings.json");try{if((0,D.existsSync)(e)){let t=JSON.parse((0,D.readFileSync)(e,"utf-8")),s=t.env??t;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return r}var O=jt(),v=process.env.CLAUDE_CONFIG_DIR||(0,g.join)((0,se.homedir)(),".claude"),Os=(0,g.join)(v,"plugins","marketplaces","bjlee2024"),Xt=(0,g.join)(O,"archives"),Bt=(0,g.join)(O,"logs"),Wt=(0,g.join)(O,"trash"),Vt=(0,g.join)(O,"backups"),qt=(0,g.join)(O,"modes"),Rs=(0,g.join)(O,"settings.json"),Ne=(0,g.join)(O,"claude-mem.db"),Yt=(0,g.join)(O,"vector-db"),Ce=(0,g.join)(O,"observer-sessions"),re=(0,g.basename)(Ce),As=(0,g.join)(v,"settings.json"),Ns=(0,g.join)(v,"commands"),Cs=(0,g.join)(v,"CLAUDE.md");function Ie(r){(0,D.mkdirSync)(r,{recursive:!0})}function Le(){return(0,g.join)(Gt,"..")}var x={dataDir:()=>O,workerPid:()=>(0,g.join)(O,"worker.pid"),serverBetaPid:()=>(0,g.join)(O,".server-beta.pid"),serverBetaPort:()=>(0,g.join)(O,".server-beta.port"),serverBetaRuntime:()=>(0,g.join)(O,".server-beta.runtime.json"),settings:()=>(0,g.join)(O,"settings.json"),database:()=>(0,g.join)(O,"claude-mem.db"),chroma:()=>(0,g.join)(O,"chroma"),combinedCerts:()=>(0,g.join)(O,"combined_certs.pem"),transcriptsConfig:()=>(0,g.join)(O,"transcript-watch.json"),transcriptsState:()=>(0,g.join)(O,"transcript-watch-state.json"),corpora:()=>(0,g.join)(O,"corpora"),supervisorRegistry:()=>(0,g.join)(O,"supervisor.json"),envFile:()=>(0,g.join)(O,".env"),logsDir:()=>Bt,archives:()=>Xt,trash:()=>Wt,backups:()=>Vt,modes:()=>qt,vectorDb:()=>Yt,observerSessions:()=>Ce};var xe=require("crypto");var De=require("os"),ve=U(require("path"),1),ye=require("child_process");var X=require("fs"),j=U(require("path"),1);var w={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Me(r){let e=j.default.join(r,".git"),t;try{t=(0,X.statSync)(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&u.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),w}if(!t.isFile())return w;let s;try{s=(0,X.readFileSync)(e,"utf-8").trim()}catch(c){return u.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),w}let n=s.match(/^gitdir:\s*(.+)$/);if(!n)return w;let i=n[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!i)return w;let a=i[1],d=j.default.basename(r),l=j.default.basename(a);return{isWorktree:!0,worktreeName:d,parentRepoPath:a,parentProjectName:l}}function Ue(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,De.homedir)()):r}function Jt(r){try{return(0,ye.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Qt(r){if(!r||r.trim()==="")return u.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Ue(r),s=Jt(e)??e,n=ve.default.basename(s);if(n===""){if(process.platform==="win32"){let i=r.match(/^([A-Z]):\\/i);if(i){let d=`drive-${i[1].toUpperCase()}`;return u.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:d}),d}}return u.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return n}function ne(r){let e=Qt(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Ue(r),s=Me(t);if(s.isWorktree&&s.parentProjectName){let n=`${s.parentProjectName}/${e}`;return{primary:n,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,n]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}function B(r,e,t){return(0,xe.createHash)("sha256").update([r||"",e||"",t||""].join("\0")).digest("hex").slice(0,16)}function oe(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[String(e)]}catch{return[r]}}var N="claude";function zt(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function y(r){if(!r)return N;let e=zt(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:N}function we(r){let e=["claude","codex","cursor"];return[...r].sort((t,s)=>{let n=e.indexOf(t),o=e.indexOf(s);return n!==-1||o!==-1?n===-1?1:o===-1?-1:n-o:t.localeCompare(s)})}function Zt(r,e){return{customTitle:r,platformSource:e?y(e):void 0}}var W=class{db;constructor(e=Ne){e instanceof ie.Database?this.db=e:(e!==":memory:"&&Ie(O),this.db=new ie.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA foreign_keys = ON"),this.db.run("PRAGMA journal_size_limit = 4194304")),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable(),this.ensureDiscoveryTokensColumn(),this.createPendingMessagesTable(),this.renameSessionIdColumns(),this.repairSessionIdColumnRename(),this.addFailedAtEpochColumn(),this.addOnUpdateCascadeToForeignKeys(),this.addObservationContentHashColumn(),this.addSessionCustomTitleColumn(),this.addSessionPlatformSourceColumn(),this.addObservationModelColumns(),this.ensureMergedIntoProjectColumns(),this.addObservationSubagentColumns(),this.addObservationsUniqueContentHashIndex(),this.addObservationsMetadataColumn(),this.dropDeadPendingMessagesColumns(),this.ensurePendingMessagesToolUseIdColumn(),this.dropWorkerPidColumn()}dropWorkerPidColumn(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(32),s=this.db.query("PRAGMA table_info(pending_messages)").all().some(n=>n.name==="worker_pid");if(!(e&&!s)){if(s)try{this.db.run("DROP INDEX IF EXISTS idx_pending_messages_worker_pid"),this.db.run("ALTER TABLE pending_messages DROP COLUMN worker_pid"),u.debug("DB","Dropped worker_pid column and its index from pending_messages")}catch(n){u.warn("DB","Failed to drop worker_pid column from pending_messages",{},n instanceof Error?n:new Error(String(n)));return}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(32,new Date().toISOString())}}dropDeadPendingMessagesColumns(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(31),t=this.db.query("PRAGMA table_info(pending_messages)").all(),s=new Set(t.map(i=>i.name)),o=["retry_count","failed_at_epoch","completed_at_epoch"].filter(i=>s.has(i));if(!(e&&o.length===0)){if(o.length>0){this.db.run("BEGIN TRANSACTION");try{this.db.run("DELETE FROM pending_messages WHERE status NOT IN ('pending', 'processing')");for(let i of o)this.db.run(`ALTER TABLE pending_messages DROP COLUMN ${i}`),u.debug("DB",`Dropped dead column ${i} from pending_messages`);e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(31,new Date().toISOString()),this.db.run("COMMIT")}catch(i){this.db.run("ROLLBACK"),u.warn("DB","Failed to drop dead columns from pending_messages",{},i instanceof Error?i:new Error(String(i)));return}return}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(31,new Date().toISOString())}}initializeSchema(){this.db.run(`
10
+ CREATE TABLE IF NOT EXISTS schema_versions (
11
+ id INTEGER PRIMARY KEY,
12
+ version INTEGER UNIQUE NOT NULL,
13
+ applied_at TEXT NOT NULL
14
+ )
15
+ `),this.db.run(`
16
+ CREATE TABLE IF NOT EXISTS sdk_sessions (
17
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
18
+ content_session_id TEXT UNIQUE NOT NULL,
19
+ memory_session_id TEXT UNIQUE,
20
+ project TEXT NOT NULL,
21
+ platform_source TEXT NOT NULL DEFAULT 'claude',
22
+ user_prompt TEXT,
23
+ started_at TEXT NOT NULL,
24
+ started_at_epoch INTEGER NOT NULL,
25
+ completed_at TEXT,
26
+ completed_at_epoch INTEGER,
27
+ status TEXT CHECK(status IN ('active', 'completed', 'failed')) NOT NULL DEFAULT 'active'
28
+ );
29
+
30
+ CREATE INDEX IF NOT EXISTS idx_sdk_sessions_claude_id ON sdk_sessions(content_session_id);
31
+ CREATE INDEX IF NOT EXISTS idx_sdk_sessions_sdk_id ON sdk_sessions(memory_session_id);
32
+ CREATE INDEX IF NOT EXISTS idx_sdk_sessions_project ON sdk_sessions(project);
33
+ CREATE INDEX IF NOT EXISTS idx_sdk_sessions_status ON sdk_sessions(status);
34
+ CREATE INDEX IF NOT EXISTS idx_sdk_sessions_started ON sdk_sessions(started_at_epoch DESC);
35
+
36
+ CREATE TABLE IF NOT EXISTS observations (
37
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
38
+ memory_session_id TEXT NOT NULL,
39
+ project TEXT NOT NULL,
40
+ text TEXT NOT NULL,
41
+ type TEXT NOT NULL,
42
+ created_at TEXT NOT NULL,
43
+ created_at_epoch INTEGER NOT NULL,
44
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE ON UPDATE CASCADE
45
+ );
46
+
47
+ CREATE INDEX IF NOT EXISTS idx_observations_sdk_session ON observations(memory_session_id);
48
+ CREATE INDEX IF NOT EXISTS idx_observations_project ON observations(project);
49
+ CREATE INDEX IF NOT EXISTS idx_observations_type ON observations(type);
50
+ CREATE INDEX IF NOT EXISTS idx_observations_created ON observations(created_at_epoch DESC);
51
+
52
+ CREATE TABLE IF NOT EXISTS session_summaries (
53
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
54
+ memory_session_id TEXT UNIQUE NOT NULL,
55
+ project TEXT NOT NULL,
56
+ request TEXT,
57
+ investigated TEXT,
58
+ learned TEXT,
59
+ completed TEXT,
60
+ next_steps TEXT,
61
+ files_read TEXT,
62
+ files_edited TEXT,
63
+ notes TEXT,
64
+ created_at TEXT NOT NULL,
65
+ created_at_epoch INTEGER NOT NULL,
66
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE ON UPDATE CASCADE
67
+ );
68
+
69
+ CREATE INDEX IF NOT EXISTS idx_session_summaries_sdk_session ON session_summaries(memory_session_id);
70
+ CREATE INDEX IF NOT EXISTS idx_session_summaries_project ON session_summaries(project);
71
+ CREATE INDEX IF NOT EXISTS idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
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"),u.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"),u.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"),u.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"),u.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&&s.origin!=="pk")){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString());return}u.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(`
73
+ CREATE TABLE session_summaries_new (
74
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
75
+ memory_session_id TEXT NOT NULL,
76
+ project TEXT NOT NULL,
77
+ request TEXT,
78
+ investigated TEXT,
79
+ learned TEXT,
80
+ completed TEXT,
81
+ next_steps TEXT,
82
+ files_read TEXT,
83
+ files_edited TEXT,
84
+ notes TEXT,
85
+ prompt_number INTEGER,
86
+ created_at TEXT NOT NULL,
87
+ created_at_epoch INTEGER NOT NULL,
88
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE
89
+ )
90
+ `),this.db.run(`
91
+ INSERT INTO session_summaries_new
92
+ SELECT id, memory_session_id, project, request, investigated, learned,
93
+ completed, next_steps, files_read, files_edited, notes,
94
+ prompt_number, created_at, created_at_epoch
95
+ FROM session_summaries
96
+ `),this.db.run("DROP TABLE session_summaries"),this.db.run("ALTER TABLE session_summaries_new RENAME TO session_summaries"),this.db.run(`
97
+ CREATE INDEX idx_session_summaries_sdk_session ON session_summaries(memory_session_id);
98
+ CREATE INDEX idx_session_summaries_project ON session_summaries(project);
99
+ CREATE INDEX idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
100
+ `),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString()),u.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}u.debug("DB","Adding hierarchical fields to observations table"),this.db.run(`
101
+ ALTER TABLE observations ADD COLUMN title TEXT;
102
+ ALTER TABLE observations ADD COLUMN subtitle TEXT;
103
+ ALTER TABLE observations ADD COLUMN facts TEXT;
104
+ ALTER TABLE observations ADD COLUMN narrative TEXT;
105
+ ALTER TABLE observations ADD COLUMN concepts TEXT;
106
+ ALTER TABLE observations ADD COLUMN files_read TEXT;
107
+ ALTER TABLE observations ADD COLUMN files_modified TEXT;
108
+ `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString()),u.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}u.debug("DB","Making observations.text nullable"),this.db.run("BEGIN TRANSACTION"),this.db.run("DROP TABLE IF EXISTS observations_new"),this.db.run(`
109
+ CREATE TABLE observations_new (
110
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
111
+ memory_session_id TEXT NOT NULL,
112
+ project TEXT NOT NULL,
113
+ text TEXT,
114
+ type TEXT NOT NULL,
115
+ title TEXT,
116
+ subtitle TEXT,
117
+ facts TEXT,
118
+ narrative TEXT,
119
+ concepts TEXT,
120
+ files_read TEXT,
121
+ files_modified TEXT,
122
+ prompt_number INTEGER,
123
+ created_at TEXT NOT NULL,
124
+ created_at_epoch INTEGER NOT NULL,
125
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE
126
+ )
127
+ `),this.db.run(`
128
+ INSERT INTO observations_new
129
+ SELECT id, memory_session_id, project, text, type, title, subtitle, facts,
130
+ narrative, concepts, files_read, files_modified, prompt_number,
131
+ created_at, created_at_epoch
132
+ FROM observations
133
+ `),this.db.run("DROP TABLE observations"),this.db.run("ALTER TABLE observations_new RENAME TO observations"),this.db.run(`
134
+ CREATE INDEX idx_observations_sdk_session ON observations(memory_session_id);
135
+ CREATE INDEX idx_observations_project ON observations(project);
136
+ CREATE INDEX idx_observations_type ON observations(type);
137
+ CREATE INDEX idx_observations_created ON observations(created_at_epoch DESC);
138
+ `),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString()),u.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}u.debug("DB","Creating user_prompts table with FTS5 support"),this.db.run("BEGIN TRANSACTION"),this.db.run(`
139
+ CREATE TABLE user_prompts (
140
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
141
+ content_session_id TEXT NOT NULL,
142
+ prompt_number INTEGER NOT NULL,
143
+ prompt_text TEXT NOT NULL,
144
+ created_at TEXT NOT NULL,
145
+ created_at_epoch INTEGER NOT NULL,
146
+ FOREIGN KEY(content_session_id) REFERENCES sdk_sessions(content_session_id) ON DELETE CASCADE
147
+ );
148
+
149
+ CREATE INDEX idx_user_prompts_claude_session ON user_prompts(content_session_id);
150
+ CREATE INDEX idx_user_prompts_created ON user_prompts(created_at_epoch DESC);
151
+ CREATE INDEX idx_user_prompts_prompt_number ON user_prompts(prompt_number);
152
+ CREATE INDEX idx_user_prompts_lookup ON user_prompts(content_session_id, prompt_number);
153
+ `);let s=`
154
+ CREATE VIRTUAL TABLE user_prompts_fts USING fts5(
155
+ prompt_text,
156
+ content='user_prompts',
157
+ content_rowid='id'
158
+ );
159
+ `,n=`
160
+ CREATE TRIGGER user_prompts_ai AFTER INSERT ON user_prompts BEGIN
161
+ INSERT INTO user_prompts_fts(rowid, prompt_text)
162
+ VALUES (new.id, new.prompt_text);
163
+ END;
164
+
165
+ CREATE TRIGGER user_prompts_ad AFTER DELETE ON user_prompts BEGIN
166
+ INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text)
167
+ VALUES('delete', old.id, old.prompt_text);
168
+ END;
169
+
170
+ CREATE TRIGGER user_prompts_au AFTER UPDATE ON user_prompts BEGIN
171
+ INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text)
172
+ VALUES('delete', old.id, old.prompt_text);
173
+ INSERT INTO user_prompts_fts(rowid, prompt_text)
174
+ VALUES (new.id, new.prompt_text);
175
+ END;
176
+ `;try{this.db.run(s),this.db.run(n)}catch(o){o instanceof Error?u.warn("DB","FTS5 not available \u2014 user_prompts_fts skipped (search uses ChromaDB)",{},o):u.warn("DB","FTS5 not available \u2014 user_prompts_fts skipped (search uses ChromaDB)",{},new Error(String(o))),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString()),u.debug("DB","Created user_prompts table (without FTS5)");return}this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString()),u.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"),u.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"),u.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}u.debug("DB","Creating pending_messages table"),this.db.run(`
177
+ CREATE TABLE pending_messages (
178
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
179
+ session_db_id INTEGER NOT NULL,
180
+ content_session_id TEXT NOT NULL,
181
+ message_type TEXT NOT NULL CHECK(message_type IN ('observation', 'summarize')),
182
+ tool_name TEXT,
183
+ tool_input TEXT,
184
+ tool_response TEXT,
185
+ cwd TEXT,
186
+ last_user_message TEXT,
187
+ last_assistant_message TEXT,
188
+ prompt_number INTEGER,
189
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'processing')),
190
+ created_at_epoch INTEGER NOT NULL,
191
+ FOREIGN KEY (session_db_id) REFERENCES sdk_sessions(id) ON DELETE CASCADE
192
+ )
193
+ `),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_session ON pending_messages(session_db_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_status ON pending_messages(status)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_claude_session ON pending_messages(content_session_id)"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(16,new Date().toISOString()),u.debug("DB","pending_messages table created successfully")}renameSessionIdColumns(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(17))return;u.debug("DB","Checking session ID columns for semantic clarity rename");let t=0,s=(n,o,i)=>{let a=this.db.query(`PRAGMA table_info(${n})`).all(),d=a.some(c=>c.name===o);return a.some(c=>c.name===i)?!1:d?(this.db.run(`ALTER TABLE ${n} RENAME COLUMN ${o} TO ${i}`),u.debug("DB",`Renamed ${n}.${o} to ${i}`),!0):(u.warn("DB",`Column ${o} not found in ${n}, skipping rename`),!1)};s("sdk_sessions","claude_session_id","content_session_id")&&t++,s("sdk_sessions","sdk_session_id","memory_session_id")&&t++,s("pending_messages","claude_session_id","content_session_id")&&t++,s("observations","sdk_session_id","memory_session_id")&&t++,s("session_summaries","sdk_session_id","memory_session_id")&&t++,s("user_prompts","claude_session_id","content_session_id")&&t++,this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(17,new Date().toISOString()),t>0?u.debug("DB",`Successfully renamed ${t} session ID columns`):u.debug("DB","No session ID column renames needed (already up to date)")}repairSessionIdColumnRename(){this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(19)||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(19,new Date().toISOString())}addFailedAtEpochColumn(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(20))return;this.db.query("PRAGMA table_info(pending_messages)").all().some(n=>n.name==="failed_at_epoch")||(this.db.run("ALTER TABLE pending_messages ADD COLUMN failed_at_epoch INTEGER"),u.debug("DB","Added failed_at_epoch column to pending_messages table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(20,new Date().toISOString())}addOnUpdateCascadeToForeignKeys(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(21))return;u.debug("DB","Adding ON UPDATE CASCADE to FK constraints on observations and session_summaries"),this.db.run("PRAGMA foreign_keys = OFF"),this.db.run("BEGIN TRANSACTION"),this.db.run("DROP TRIGGER IF EXISTS observations_ai"),this.db.run("DROP TRIGGER IF EXISTS observations_ad"),this.db.run("DROP TRIGGER IF EXISTS observations_au"),this.db.run("DROP TABLE IF EXISTS observations_new");let s=this.db.query("PRAGMA table_info(observations)").all().some(f=>f.name==="metadata"),n=s?`,
194
+ metadata TEXT`:"",o=s?", metadata":"",i=`
195
+ CREATE TABLE observations_new (
196
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
197
+ memory_session_id TEXT NOT NULL,
198
+ project TEXT NOT NULL,
199
+ text TEXT,
200
+ type TEXT NOT NULL,
201
+ title TEXT,
202
+ subtitle TEXT,
203
+ facts TEXT,
204
+ narrative TEXT,
205
+ concepts TEXT,
206
+ files_read TEXT,
207
+ files_modified TEXT,
208
+ prompt_number INTEGER,
209
+ discovery_tokens INTEGER DEFAULT 0,
210
+ created_at TEXT NOT NULL,
211
+ created_at_epoch INTEGER NOT NULL${n},
212
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE ON UPDATE CASCADE
213
+ )
214
+ `,a=`
215
+ INSERT INTO observations_new
216
+ SELECT id, memory_session_id, project, text, type, title, subtitle, facts,
217
+ narrative, concepts, files_read, files_modified, prompt_number,
218
+ discovery_tokens, created_at, created_at_epoch${o}
219
+ FROM observations
220
+ `,d=`
221
+ CREATE INDEX idx_observations_sdk_session ON observations(memory_session_id);
222
+ CREATE INDEX idx_observations_project ON observations(project);
223
+ CREATE INDEX idx_observations_type ON observations(type);
224
+ CREATE INDEX idx_observations_created ON observations(created_at_epoch DESC);
225
+ `,l=`
226
+ CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN
227
+ INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts)
228
+ VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts);
229
+ END;
230
+
231
+ CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN
232
+ INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts)
233
+ VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts);
234
+ END;
235
+
236
+ CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN
237
+ INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts)
238
+ VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts);
239
+ INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts)
240
+ VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts);
241
+ END;
242
+ `;this.db.run("DROP TRIGGER IF EXISTS session_summaries_ai"),this.db.run("DROP TRIGGER IF EXISTS session_summaries_ad"),this.db.run("DROP TRIGGER IF EXISTS session_summaries_au"),this.db.run("DROP TABLE IF EXISTS session_summaries_new");let c=`
243
+ CREATE TABLE session_summaries_new (
244
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
245
+ memory_session_id TEXT NOT NULL,
246
+ project TEXT NOT NULL,
247
+ request TEXT,
248
+ investigated TEXT,
249
+ learned TEXT,
250
+ completed TEXT,
251
+ next_steps TEXT,
252
+ files_read TEXT,
253
+ files_edited TEXT,
254
+ notes TEXT,
255
+ prompt_number INTEGER,
256
+ discovery_tokens INTEGER DEFAULT 0,
257
+ created_at TEXT NOT NULL,
258
+ created_at_epoch INTEGER NOT NULL,
259
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE ON UPDATE CASCADE
260
+ )
261
+ `,T=`
262
+ INSERT INTO session_summaries_new
263
+ SELECT id, memory_session_id, project, request, investigated, learned,
264
+ completed, next_steps, files_read, files_edited, notes,
265
+ prompt_number, discovery_tokens, created_at, created_at_epoch
266
+ FROM session_summaries
267
+ `,p=`
268
+ CREATE INDEX idx_session_summaries_sdk_session ON session_summaries(memory_session_id);
269
+ CREATE INDEX idx_session_summaries_project ON session_summaries(project);
270
+ CREATE INDEX idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
271
+ `,E=`
272
+ CREATE TRIGGER IF NOT EXISTS session_summaries_ai AFTER INSERT ON session_summaries BEGIN
273
+ INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
274
+ VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes);
275
+ END;
276
+
277
+ CREATE TRIGGER IF NOT EXISTS session_summaries_ad AFTER DELETE ON session_summaries BEGIN
278
+ INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes)
279
+ VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes);
280
+ END;
281
+
282
+ CREATE TRIGGER IF NOT EXISTS session_summaries_au AFTER UPDATE ON session_summaries BEGIN
283
+ INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes)
284
+ VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes);
285
+ INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
286
+ VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes);
287
+ END;
288
+ `;try{this.recreateObservationsWithCascade(i,a,d,l),this.recreateSessionSummariesWithCascade(c,T,p,E),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(21,new Date().toISOString()),this.db.run("COMMIT"),this.db.run("PRAGMA foreign_keys = ON"),u.debug("DB","Successfully added ON UPDATE CASCADE to FK constraints")}catch(f){throw this.db.run("ROLLBACK"),this.db.run("PRAGMA foreign_keys = ON"),f instanceof Error?f:new Error(String(f))}}recreateObservationsWithCascade(e,t,s,n){this.db.run(e),this.db.run(t),this.db.run("DROP TABLE observations"),this.db.run("ALTER TABLE observations_new RENAME TO observations"),this.db.run(s),this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='observations_fts'").all().length>0&&this.db.run(n)}recreateSessionSummariesWithCascade(e,t,s,n){this.db.run(e),this.db.run(t),this.db.run("DROP TABLE session_summaries"),this.db.run("ALTER TABLE session_summaries_new RENAME TO session_summaries"),this.db.run(s),this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='session_summaries_fts'").all().length>0&&this.db.run(n)}addObservationContentHashColumn(){if(this.db.query("PRAGMA table_info(observations)").all().some(s=>s.name==="content_hash")){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(22,new Date().toISOString());return}this.db.run("ALTER TABLE observations ADD COLUMN content_hash TEXT"),this.db.run("UPDATE observations SET content_hash = substr(hex(randomblob(8)), 1, 16) WHERE content_hash IS NULL"),this.db.run("CREATE INDEX IF NOT EXISTS idx_observations_content_hash ON observations(content_hash, created_at_epoch)"),u.debug("DB","Added content_hash column to observations table with backfill and index"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(22,new Date().toISOString())}addSessionCustomTitleColumn(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(23))return;this.db.query("PRAGMA table_info(sdk_sessions)").all().some(n=>n.name==="custom_title")||(this.db.run("ALTER TABLE sdk_sessions ADD COLUMN custom_title TEXT"),u.debug("DB","Added custom_title column to sdk_sessions table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(23,new Date().toISOString())}addSessionPlatformSourceColumn(){let t=this.db.query("PRAGMA table_info(sdk_sessions)").all().some(i=>i.name==="platform_source"),n=this.db.query("PRAGMA index_list(sdk_sessions)").all().some(i=>i.name==="idx_sdk_sessions_platform_source");this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(24)&&t&&n||(t||(this.db.run(`ALTER TABLE sdk_sessions ADD COLUMN platform_source TEXT NOT NULL DEFAULT '${N}'`),u.debug("DB","Added platform_source column to sdk_sessions table")),this.db.run(`
289
+ UPDATE sdk_sessions
290
+ SET platform_source = '${N}'
291
+ WHERE platform_source IS NULL OR platform_source = ''
292
+ `),n||this.db.run("CREATE INDEX IF NOT EXISTS idx_sdk_sessions_platform_source ON sdk_sessions(platform_source)"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(24,new Date().toISOString()))}addObservationModelColumns(){let e=this.db.query("PRAGMA table_info(observations)").all(),t=e.some(n=>n.name==="generated_by_model"),s=e.some(n=>n.name==="relevance_count");t&&s||(t||this.db.run("ALTER TABLE observations ADD COLUMN generated_by_model TEXT"),s||this.db.run("ALTER TABLE observations ADD COLUMN relevance_count INTEGER DEFAULT 0"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(26,new Date().toISOString()))}ensureMergedIntoProjectColumns(){this.db.query("PRAGMA table_info(observations)").all().some(s=>s.name==="merged_into_project")||this.db.run("ALTER TABLE observations ADD COLUMN merged_into_project TEXT"),this.db.run("CREATE INDEX IF NOT EXISTS idx_observations_merged_into ON observations(merged_into_project)"),this.db.query("PRAGMA table_info(session_summaries)").all().some(s=>s.name==="merged_into_project")||this.db.run("ALTER TABLE session_summaries ADD COLUMN merged_into_project TEXT"),this.db.run("CREATE INDEX IF NOT EXISTS idx_summaries_merged_into ON session_summaries(merged_into_project)")}addObservationSubagentColumns(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(27),t=this.db.query("PRAGMA table_info(observations)").all(),s=t.some(i=>i.name==="agent_type"),n=t.some(i=>i.name==="agent_id");s||this.db.run("ALTER TABLE observations ADD COLUMN agent_type TEXT"),n||this.db.run("ALTER TABLE observations ADD COLUMN agent_id TEXT"),this.db.run("CREATE INDEX IF NOT EXISTS idx_observations_agent_type ON observations(agent_type)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_observations_agent_id ON observations(agent_id)");let o=this.db.query("PRAGMA table_info(pending_messages)").all();if(o.length>0){let i=o.some(d=>d.name==="agent_type"),a=o.some(d=>d.name==="agent_id");i||this.db.run("ALTER TABLE pending_messages ADD COLUMN agent_type TEXT"),a||this.db.run("ALTER TABLE pending_messages ADD COLUMN agent_id TEXT")}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(27,new Date().toISOString())}ensurePendingMessagesToolUseIdColumn(){if(this.db.query("SELECT name FROM sqlite_master WHERE type='table' AND name='pending_messages'").all().length===0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(28,new Date().toISOString());return}this.db.query("PRAGMA table_info(pending_messages)").all().some(n=>n.name==="tool_use_id")||this.db.run("ALTER TABLE pending_messages ADD COLUMN tool_use_id TEXT"),this.db.run("BEGIN TRANSACTION");try{this.db.run(`
293
+ DELETE FROM pending_messages
294
+ WHERE id IN (
295
+ SELECT id
296
+ FROM (
297
+ SELECT id,
298
+ ROW_NUMBER() OVER (
299
+ PARTITION BY content_session_id, tool_use_id
300
+ ORDER BY CASE status
301
+ WHEN 'processing' THEN 0
302
+ WHEN 'pending' THEN 1
303
+ ELSE 2
304
+ END, id
305
+ ) AS duplicate_rank
306
+ FROM pending_messages
307
+ WHERE tool_use_id IS NOT NULL
308
+ )
309
+ WHERE duplicate_rank > 1
310
+ )
311
+ `),this.db.run(`
312
+ -- tool_use_id is optional for summaries and legacy rows; enforce de-dupe
313
+ -- only for rows that came from a concrete tool-use event.
314
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_pending_session_tool
315
+ ON pending_messages(content_session_id, tool_use_id)
316
+ WHERE tool_use_id IS NOT NULL
317
+ `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(28,new Date().toISOString()),this.db.run("COMMIT")}catch(n){throw this.db.run("ROLLBACK"),n}}addObservationsUniqueContentHashIndex(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(29))return;let t=this.db.query("PRAGMA table_info(observations)").all(),s=t.some(o=>o.name==="memory_session_id"),n=t.some(o=>o.name==="content_hash");if(!s||!n){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(29,new Date().toISOString());return}this.db.run("BEGIN TRANSACTION");try{this.db.run(`
318
+ DELETE FROM observations
319
+ WHERE id NOT IN (
320
+ SELECT MIN(id) FROM observations
321
+ GROUP BY memory_session_id, content_hash
322
+ )
323
+ `),this.db.run(`
324
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_observations_session_hash
325
+ ON observations(memory_session_id, content_hash)
326
+ `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(29,new Date().toISOString()),this.db.run("COMMIT")}catch(o){throw this.db.run("ROLLBACK"),o}}addObservationsMetadataColumn(){this.db.query("PRAGMA table_info(observations)").all().some(s=>s.name==="metadata")||(this.db.run("ALTER TABLE observations ADD COLUMN metadata TEXT"),u.debug("DB","Added metadata column to observations table (#2116)")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(30,new Date().toISOString())}updateMemorySessionId(e,t){this.db.prepare(`
327
+ UPDATE sdk_sessions
328
+ SET memory_session_id = ?
329
+ WHERE id = ?
330
+ `).run(t,e)}markSessionCompleted(e){let t=Date.now(),s=new Date(t).toISOString();this.db.prepare(`
331
+ UPDATE sdk_sessions
332
+ SET status = 'completed', completed_at = ?, completed_at_epoch = ?
333
+ WHERE id = ?
334
+ `).run(s,t,e)}ensureMemorySessionIdRegistered(e,t,s){let n=this.db.prepare(`
335
+ SELECT id, memory_session_id, worker_port FROM sdk_sessions WHERE id = ?
336
+ `).get(e);if(!n)throw new Error(`Session ${e} not found in sdk_sessions`);n.memory_session_id!==t&&(this.db.prepare(`
337
+ UPDATE sdk_sessions SET memory_session_id = ? WHERE id = ?
338
+ `).run(t,e),u.info("DB","Registered memory_session_id before storage (FK fix)",{sessionDbId:e,oldId:n.memory_session_id,newId:t})),typeof s=="number"&&n.worker_port!==s&&this.db.prepare(`
339
+ UPDATE sdk_sessions SET worker_port = ? WHERE id = ?
340
+ `).run(s,e)}getRecentSummaries(e,t=10){return this.db.prepare(`
341
+ SELECT
342
+ request, investigated, learned, completed, next_steps,
343
+ files_read, files_edited, notes, prompt_number, created_at
344
+ FROM session_summaries
345
+ WHERE project = ?
346
+ ORDER BY created_at_epoch DESC
347
+ LIMIT ?
348
+ `).all(e,t)}getRecentSummariesWithSessionInfo(e,t=3){return this.db.prepare(`
349
+ SELECT
350
+ memory_session_id, request, learned, completed, next_steps,
351
+ prompt_number, created_at
352
+ FROM session_summaries
353
+ WHERE project = ?
354
+ ORDER BY created_at_epoch DESC
355
+ LIMIT ?
356
+ `).all(e,t)}getRecentObservations(e,t=20){return this.db.prepare(`
357
+ SELECT type, text, prompt_number, created_at
358
+ FROM observations
359
+ WHERE project = ?
360
+ ORDER BY created_at_epoch DESC
361
+ LIMIT ?
362
+ `).all(e,t)}getAllRecentObservations(e=100){return this.db.prepare(`
363
+ SELECT
364
+ o.id,
365
+ o.type,
366
+ o.title,
367
+ o.subtitle,
368
+ o.text,
369
+ o.project,
370
+ COALESCE(s.platform_source, '${N}') as platform_source,
371
+ o.prompt_number,
372
+ o.created_at,
373
+ o.created_at_epoch
374
+ FROM observations o
375
+ LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
376
+ ORDER BY o.created_at_epoch DESC
377
+ LIMIT ?
378
+ `).all(e)}getAllRecentSummaries(e=50){return this.db.prepare(`
379
+ SELECT
380
+ ss.id,
381
+ ss.request,
382
+ ss.investigated,
383
+ ss.learned,
384
+ ss.completed,
385
+ ss.next_steps,
386
+ ss.files_read,
387
+ ss.files_edited,
388
+ ss.notes,
389
+ ss.project,
390
+ COALESCE(s.platform_source, '${N}') as platform_source,
391
+ ss.prompt_number,
392
+ ss.created_at,
393
+ ss.created_at_epoch
394
+ FROM session_summaries ss
395
+ LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
396
+ ORDER BY ss.created_at_epoch DESC
397
+ LIMIT ?
398
+ `).all(e)}getAllRecentUserPrompts(e=100){return this.db.prepare(`
399
+ SELECT
400
+ up.id,
401
+ up.content_session_id,
402
+ s.project,
403
+ COALESCE(s.platform_source, '${N}') as platform_source,
404
+ up.prompt_number,
405
+ up.prompt_text,
406
+ up.created_at,
407
+ up.created_at_epoch
408
+ FROM user_prompts up
409
+ LEFT JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
410
+ ORDER BY up.created_at_epoch DESC
411
+ LIMIT ?
412
+ `).all(e)}getAllProjects(e){let t=e?y(e):void 0,s=`
413
+ SELECT DISTINCT project
414
+ FROM sdk_sessions
415
+ WHERE project IS NOT NULL AND project != ''
416
+ AND project != ?
417
+ `,n=[re];return t&&(s+=" AND COALESCE(platform_source, ?) = ?",n.push(N,t)),s+=" ORDER BY project ASC",this.db.prepare(s).all(...n).map(i=>i.project)}getProjectCatalog(){let e=this.db.prepare(`
418
+ SELECT
419
+ COALESCE(platform_source, '${N}') as platform_source,
420
+ project,
421
+ MAX(started_at_epoch) as latest_epoch
422
+ FROM sdk_sessions
423
+ WHERE project IS NOT NULL AND project != ''
424
+ AND project != ?
425
+ GROUP BY COALESCE(platform_source, '${N}'), project
426
+ ORDER BY latest_epoch DESC
427
+ `).all(re),t=[],s=new Set,n={};for(let i of e){let a=y(i.platform_source);n[a]||(n[a]=[]),n[a].includes(i.project)||n[a].push(i.project),s.has(i.project)||(s.add(i.project),t.push(i.project))}let o=we(Object.keys(n));return{projects:t,sources:o,projectsBySource:Object.fromEntries(o.map(i=>[i,n[i]||[]]))}}getLatestUserPrompt(e){return this.db.prepare(`
428
+ SELECT
429
+ up.*,
430
+ s.memory_session_id,
431
+ s.project,
432
+ COALESCE(s.platform_source, '${N}') as platform_source
433
+ FROM user_prompts up
434
+ JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
435
+ WHERE up.content_session_id = ?
436
+ ORDER BY up.created_at_epoch DESC
437
+ LIMIT 1
438
+ `).get(e)}getRecentSessionsWithStatus(e,t=3){return this.db.prepare(`
439
+ SELECT * FROM (
440
+ SELECT
441
+ s.memory_session_id,
442
+ s.status,
443
+ s.started_at,
444
+ s.started_at_epoch,
445
+ s.user_prompt,
446
+ CASE WHEN sum.memory_session_id IS NOT NULL THEN 1 ELSE 0 END as has_summary
447
+ FROM sdk_sessions s
448
+ LEFT JOIN session_summaries sum ON s.memory_session_id = sum.memory_session_id
449
+ WHERE s.project = ? AND s.memory_session_id IS NOT NULL
450
+ GROUP BY s.memory_session_id
451
+ ORDER BY s.started_at_epoch DESC
452
+ LIMIT ?
453
+ )
454
+ ORDER BY started_at_epoch ASC
455
+ `).all(e,t)}getObservationsForSession(e){return this.db.prepare(`
456
+ SELECT title, subtitle, type, prompt_number
457
+ FROM observations
458
+ WHERE memory_session_id = ?
459
+ ORDER BY created_at_epoch ASC
460
+ `).all(e)}getObservationById(e){return this.db.prepare(`
461
+ SELECT *
462
+ FROM observations
463
+ WHERE id = ?
464
+ `).get(e)||null}getObservationsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o,type:i,concepts:a,files:d}=t,l=s==="relevance",c=l?"":`ORDER BY created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,T=n?`LIMIT ${n}`:"",p=e.map(()=>"?").join(","),E=[...e],f=[];if(o&&(f.push("project = ?"),E.push(o)),i)if(Array.isArray(i)){let S=i.map(()=>"?").join(",");f.push(`type IN (${S})`),E.push(...i)}else f.push("type = ?"),E.push(i);if(a){let S=Array.isArray(a)?a:[a],R=S.map(()=>"EXISTS (SELECT 1 FROM json_each(concepts) WHERE value = ?)");E.push(...S),f.push(`(${R.join(" OR ")})`)}if(d){let S=Array.isArray(d)?d:[d],R=S.map(()=>"(EXISTS (SELECT 1 FROM json_each(files_read) WHERE value LIKE ?) OR EXISTS (SELECT 1 FROM json_each(files_modified) WHERE value LIKE ?))");S.forEach(M=>{E.push(`%${M}%`,`%${M}%`)}),f.push(`(${R.join(" OR ")})`)}let b=f.length>0?`WHERE id IN (${p}) AND ${f.join(" AND ")}`:`WHERE id IN (${p})`,A=this.db.prepare(`
465
+ SELECT *
466
+ FROM observations
467
+ ${b}
468
+ ${c}
469
+ ${T}
470
+ `).all(...E);if(!l)return A;let h=new Map(A.map(S=>[S.id,S]));return e.map(S=>h.get(S)).filter(S=>!!S)}getSummaryForSession(e){return this.db.prepare(`
471
+ SELECT
472
+ request, investigated, learned, completed, next_steps,
473
+ files_read, files_edited, notes, prompt_number, created_at,
474
+ created_at_epoch
475
+ FROM session_summaries
476
+ WHERE memory_session_id = ?
477
+ ORDER BY created_at_epoch DESC
478
+ LIMIT 1
479
+ `).get(e)||null}getFilesForSession(e){let s=this.db.prepare(`
480
+ SELECT files_read, files_modified
481
+ FROM observations
482
+ WHERE memory_session_id = ?
483
+ `).all(e),n=new Set,o=new Set;for(let i of s)oe(i.files_read).forEach(a=>n.add(a)),oe(i.files_modified).forEach(a=>o.add(a));return{filesRead:Array.from(n),filesModified:Array.from(o)}}getSessionById(e){return this.db.prepare(`
484
+ SELECT id, content_session_id, memory_session_id, project,
485
+ COALESCE(platform_source, '${N}') as platform_source,
486
+ user_prompt, custom_title, status
487
+ FROM sdk_sessions
488
+ WHERE id = ?
489
+ LIMIT 1
490
+ `).get(e)||null}getSdkSessionsBySessionIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.db.prepare(`
491
+ SELECT id, content_session_id, memory_session_id, project,
492
+ COALESCE(platform_source, '${N}') as platform_source,
493
+ user_prompt, custom_title,
494
+ started_at, started_at_epoch, completed_at, completed_at_epoch, status
495
+ FROM sdk_sessions
496
+ WHERE memory_session_id IN (${t})
497
+ ORDER BY started_at_epoch DESC
498
+ `).all(...e)}getPromptNumberFromUserPrompts(e){return this.db.prepare(`
499
+ SELECT COUNT(*) as count FROM user_prompts WHERE content_session_id = ?
500
+ `).get(e).count}createSDKSession(e,t,s,n,o){let i=new Date,a=i.getTime(),d=Zt(n,o),l=d.platformSource??N,c=this.db.prepare(`
501
+ SELECT id, platform_source FROM sdk_sessions WHERE content_session_id = ?
502
+ `).get(e);if(c){if(t&&this.db.prepare(`
503
+ UPDATE sdk_sessions SET project = ?
504
+ WHERE content_session_id = ? AND (project IS NULL OR project = '')
505
+ `).run(t,e),d.customTitle&&this.db.prepare(`
506
+ UPDATE sdk_sessions SET custom_title = ?
507
+ WHERE content_session_id = ? AND custom_title IS NULL
508
+ `).run(d.customTitle,e),d.platformSource){let p=c.platform_source?.trim()?y(c.platform_source):void 0;if(!p)this.db.prepare(`
509
+ UPDATE sdk_sessions SET platform_source = ?
510
+ WHERE content_session_id = ?
511
+ AND COALESCE(platform_source, '') = ''
512
+ `).run(d.platformSource,e);else if(p!==d.platformSource)throw new Error(`Platform source conflict for session ${e}: existing=${p}, received=${d.platformSource}`)}return c.id}return this.db.prepare(`
513
+ INSERT INTO sdk_sessions
514
+ (content_session_id, memory_session_id, project, platform_source, user_prompt, custom_title, started_at, started_at_epoch, status)
515
+ VALUES (?, NULL, ?, ?, ?, ?, ?, ?, 'active')
516
+ `).run(e,t,l,s,d.customTitle||null,i.toISOString(),a),this.db.prepare("SELECT id FROM sdk_sessions WHERE content_session_id = ?").get(e).id}saveUserPrompt(e,t,s){let n=new Date,o=n.getTime();return this.db.prepare(`
517
+ INSERT INTO user_prompts
518
+ (content_session_id, prompt_number, prompt_text, created_at, created_at_epoch)
519
+ VALUES (?, ?, ?, ?, ?)
520
+ `).run(e,t,s,n.toISOString(),o).lastInsertRowid}getUserPrompt(e,t){return this.db.prepare(`
521
+ SELECT prompt_text
522
+ FROM user_prompts
523
+ WHERE content_session_id = ? AND prompt_number = ?
524
+ LIMIT 1
525
+ `).get(e,t)?.prompt_text??null}storeObservation(e,t,s,n,o=0,i,a){let d=i??Date.now(),l=new Date(d).toISOString(),c=B(e,s.title,s.narrative),p=this.db.prepare(`
526
+ INSERT INTO observations
527
+ (memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
528
+ files_read, files_modified, prompt_number, discovery_tokens, agent_type, agent_id, content_hash, created_at, created_at_epoch,
529
+ generated_by_model, metadata)
530
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
531
+ ON CONFLICT(memory_session_id, content_hash) DO NOTHING
532
+ RETURNING id, created_at_epoch
533
+ `).get(e,t,s.type,s.title,s.subtitle,JSON.stringify(s.facts),s.narrative,JSON.stringify(s.concepts),JSON.stringify(s.files_read),JSON.stringify(s.files_modified),n||null,o,s.agent_type??null,s.agent_id??null,c,l,d,a||null,s.metadata??null);if(p)return{id:p.id,createdAtEpoch:p.created_at_epoch};let E=this.db.prepare("SELECT id, created_at_epoch FROM observations WHERE memory_session_id = ? AND content_hash = ?").get(e,c);if(!E)throw new Error(`storeObservation: ON CONFLICT without existing row for content_hash=${c}`);return{id:E.id,createdAtEpoch:E.created_at_epoch}}storeSummary(e,t,s,n,o=0,i){let a=i??Date.now(),d=new Date(a).toISOString(),c=this.db.prepare(`
534
+ INSERT INTO session_summaries
535
+ (memory_session_id, project, request, investigated, learned, completed,
536
+ next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
537
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
538
+ `).run(e,t,s.request,s.investigated,s.learned,s.completed,s.next_steps,s.notes,n||null,o,d,a);return{id:Number(c.lastInsertRowid),createdAtEpoch:a}}storeObservations(e,t,s,n,o,i=0,a,d){let l=a??Date.now(),c=new Date(l).toISOString();return this.db.transaction(()=>{let p=[],E=this.db.prepare(`
539
+ INSERT INTO observations
540
+ (memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
541
+ files_read, files_modified, prompt_number, discovery_tokens, agent_type, agent_id, content_hash, created_at, created_at_epoch,
542
+ generated_by_model)
543
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
544
+ ON CONFLICT(memory_session_id, content_hash) DO NOTHING
545
+ RETURNING id
546
+ `),f=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let m of s){let A=B(e,m.title,m.narrative),h=E.get(e,t,m.type,m.title,m.subtitle,JSON.stringify(m.facts),m.narrative,JSON.stringify(m.concepts),JSON.stringify(m.files_read),JSON.stringify(m.files_modified),o||null,i,m.agent_type??null,m.agent_id??null,A,c,l,d||null);if(h){p.push(h.id);continue}let S=f.get(e,A);if(!S)throw new Error(`storeObservations: ON CONFLICT without existing row for content_hash=${A}`);p.push(S.id)}let b=null;if(n){let A=this.db.prepare(`
547
+ INSERT INTO session_summaries
548
+ (memory_session_id, project, request, investigated, learned, completed,
549
+ next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
550
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
551
+ `).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,o||null,i,c,l);b=Number(A.lastInsertRowid)}return{observationIds:p,summaryId:b,createdAtEpoch:l}})()}storeObservationsAndMarkComplete(e,t,s,n,o,i,a,d=0,l,c){let T=l??Date.now(),p=new Date(T).toISOString();return this.db.transaction(()=>{let f=[],b=this.db.prepare(`
552
+ INSERT INTO observations
553
+ (memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
554
+ files_read, files_modified, prompt_number, discovery_tokens, agent_type, agent_id, content_hash, created_at, created_at_epoch,
555
+ generated_by_model)
556
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
557
+ ON CONFLICT(memory_session_id, content_hash) DO NOTHING
558
+ RETURNING id
559
+ `),m=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let R of s){let M=B(e,R.title,R.narrative),be=b.get(e,t,R.type,R.title,R.subtitle,JSON.stringify(R.facts),R.narrative,JSON.stringify(R.concepts),JSON.stringify(R.files_read),JSON.stringify(R.files_modified),a||null,d,R.agent_type??null,R.agent_id??null,M,p,T,c||null);if(be){f.push(be.id);continue}let he=m.get(e,M);if(!he)throw new Error(`storeObservationsAndMarkComplete: ON CONFLICT without existing row for content_hash=${M}`);f.push(he.id)}let A;if(n){let M=this.db.prepare(`
560
+ INSERT INTO session_summaries
561
+ (memory_session_id, project, request, investigated, learned, completed,
562
+ next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
563
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
564
+ `).run(e,t,n.request,n.investigated,n.learned,n.completed,n.next_steps,n.notes,a||null,d,p,T);A=Number(M.lastInsertRowid)}if(this.db.prepare(`
565
+ DELETE FROM pending_messages
566
+ WHERE id = ? AND status = 'processing'
567
+ `).run(o).changes!==1)throw new Error(`storeObservationsAndMarkComplete: failed to complete pending message ${o}`);return{observationIds:f,summaryId:A,createdAtEpoch:T}})()}getSessionSummariesByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o}=t,i=s==="relevance",a=i?"":`ORDER BY created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,d=n?`LIMIT ${n}`:"",l=e.map(()=>"?").join(","),c=[...e],T=o?`WHERE id IN (${l}) AND project = ?`:`WHERE id IN (${l})`;o&&c.push(o);let E=this.db.prepare(`
568
+ SELECT * FROM session_summaries
569
+ ${T}
570
+ ${a}
571
+ ${d}
572
+ `).all(...c);if(!i)return E;let f=new Map(E.map(b=>[b.id,b]));return e.map(b=>f.get(b)).filter(b=>!!b)}getUserPromptsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:o}=t,i=s==="relevance",a=i?"":`ORDER BY up.created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,d=n?`LIMIT ${n}`:"",l=e.map(()=>"?").join(","),c=[...e],T=o?"AND s.project = ?":"";o&&c.push(o);let E=this.db.prepare(`
573
+ SELECT
574
+ up.*,
575
+ s.project,
576
+ s.memory_session_id
577
+ FROM user_prompts up
578
+ JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
579
+ WHERE up.id IN (${l}) ${T}
580
+ ${a}
581
+ ${d}
582
+ `).all(...c);if(!i)return E;let f=new Map(E.map(b=>[b.id,b]));return e.map(b=>f.get(b)).filter(b=>!!b)}getTimelineAroundTimestamp(e,t=10,s=10,n){return this.getTimelineAroundObservation(null,e,t,s,n)}getTimelineAroundObservation(e,t,s=10,n=10,o){let i=o?"AND project = ?":"",a=o?[o]:[],d,l;if(e!==null){let m=`
583
+ SELECT id, created_at_epoch
584
+ FROM observations
585
+ WHERE id <= ? ${i}
586
+ ORDER BY id DESC
587
+ LIMIT ?
588
+ `,A=`
589
+ SELECT id, created_at_epoch
590
+ FROM observations
591
+ WHERE id >= ? ${i}
592
+ ORDER BY id ASC
593
+ LIMIT ?
594
+ `;try{let h=this.db.prepare(m).all(e,...a,s+1),S=this.db.prepare(A).all(e,...a,n+1);if(h.length===0&&S.length===0)return{observations:[],sessions:[],prompts:[]};d=h.length>0?h[h.length-1].created_at_epoch:t,l=S.length>0?S[S.length-1].created_at_epoch:t}catch(h){return h instanceof Error?u.error("DB","Error getting boundary observations",{project:o},h):u.error("DB","Error getting boundary observations with non-Error",{},new Error(String(h))),{observations:[],sessions:[],prompts:[]}}}else{let m=`
595
+ SELECT created_at_epoch
596
+ FROM observations
597
+ WHERE created_at_epoch <= ? ${i}
598
+ ORDER BY created_at_epoch DESC
599
+ LIMIT ?
600
+ `,A=`
601
+ SELECT created_at_epoch
602
+ FROM observations
603
+ WHERE created_at_epoch >= ? ${i}
604
+ ORDER BY created_at_epoch ASC
605
+ LIMIT ?
606
+ `;try{let h=this.db.prepare(m).all(t,...a,s),S=this.db.prepare(A).all(t,...a,n+1);if(h.length===0&&S.length===0)return{observations:[],sessions:[],prompts:[]};d=h.length>0?h[h.length-1].created_at_epoch:t,l=S.length>0?S[S.length-1].created_at_epoch:t}catch(h){return h instanceof Error?u.error("DB","Error getting boundary timestamps",{project:o},h):u.error("DB","Error getting boundary timestamps with non-Error",{},new Error(String(h))),{observations:[],sessions:[],prompts:[]}}}let c=`
607
+ SELECT *
608
+ FROM observations
609
+ WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${i}
610
+ ORDER BY created_at_epoch ASC
611
+ `,T=`
612
+ SELECT *
613
+ FROM session_summaries
614
+ WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${i}
615
+ ORDER BY created_at_epoch ASC
616
+ `,p=`
617
+ SELECT up.*, s.project, s.memory_session_id
618
+ FROM user_prompts up
619
+ JOIN sdk_sessions s ON up.content_session_id = s.content_session_id
620
+ WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${i.replace("project","s.project")}
621
+ ORDER BY up.created_at_epoch ASC
622
+ `,E=this.db.prepare(c).all(d,l,...a),f=this.db.prepare(T).all(d,l,...a),b=this.db.prepare(p).all(d,l,...a);return{observations:E,sessions:f.map(m=>({id:m.id,memory_session_id:m.memory_session_id,project:m.project,request:m.request,completed:m.completed,next_steps:m.next_steps,created_at:m.created_at,created_at_epoch:m.created_at_epoch})),prompts:b.map(m=>({id:m.id,content_session_id:m.content_session_id,prompt_number:m.prompt_number,prompt_text:m.prompt_text,project:m.project,created_at:m.created_at,created_at_epoch:m.created_at_epoch}))}}getPromptById(e){return this.db.prepare(`
623
+ SELECT
624
+ p.id,
625
+ p.content_session_id,
626
+ p.prompt_number,
627
+ p.prompt_text,
628
+ s.project,
629
+ p.created_at,
630
+ p.created_at_epoch
631
+ FROM user_prompts p
632
+ LEFT JOIN sdk_sessions s ON p.content_session_id = s.content_session_id
633
+ WHERE p.id = ?
634
+ LIMIT 1
635
+ `).get(e)||null}getPromptsByIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.db.prepare(`
636
+ SELECT
637
+ p.id,
638
+ p.content_session_id,
639
+ p.prompt_number,
640
+ p.prompt_text,
641
+ s.project,
642
+ p.created_at,
643
+ p.created_at_epoch
644
+ FROM user_prompts p
645
+ LEFT JOIN sdk_sessions s ON p.content_session_id = s.content_session_id
646
+ WHERE p.id IN (${t})
647
+ ORDER BY p.created_at_epoch DESC
648
+ `).all(...e)}getSessionSummaryById(e){return this.db.prepare(`
649
+ SELECT
650
+ id,
651
+ memory_session_id,
652
+ content_session_id,
653
+ project,
654
+ user_prompt,
655
+ request_summary,
656
+ learned_summary,
657
+ status,
658
+ created_at,
659
+ created_at_epoch
660
+ FROM sdk_sessions
661
+ WHERE id = ?
662
+ LIMIT 1
663
+ `).get(e)||null}getOrCreateManualSession(e){let t=`manual-${e}`,s=`manual-content-${e}`;if(this.db.prepare("SELECT memory_session_id FROM sdk_sessions WHERE memory_session_id = ?").get(t))return t;let o=new Date;return this.db.prepare(`
664
+ INSERT INTO sdk_sessions (memory_session_id, content_session_id, project, platform_source, started_at, started_at_epoch, status)
665
+ VALUES (?, ?, ?, ?, ?, ?, 'active')
666
+ `).run(t,s,e,N,o.toISOString(),o.getTime()),u.info("SESSION","Created manual session",{memorySessionId:t,project:e}),t}close(){this.db.close()}importSdkSession(e){let t=this.db.prepare("SELECT id FROM sdk_sessions WHERE content_session_id = ?").get(e.content_session_id);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(`
667
+ INSERT INTO sdk_sessions (
668
+ content_session_id, memory_session_id, project, platform_source, user_prompt,
669
+ started_at, started_at_epoch, completed_at, completed_at_epoch, status
670
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
671
+ `).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(`
672
+ INSERT INTO session_summaries (
673
+ memory_session_id, project, request, investigated, learned,
674
+ completed, next_steps, files_read, files_edited, notes,
675
+ prompt_number, discovery_tokens, created_at, created_at_epoch
676
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
677
+ `).run(e.memory_session_id,e.project,e.request,e.investigated,e.learned,e.completed,e.next_steps,e.files_read,e.files_edited,e.notes,e.prompt_number,e.discovery_tokens||0,e.created_at,e.created_at_epoch).lastInsertRowid}}importObservation(e){let t=this.db.prepare(`
678
+ SELECT id FROM observations
679
+ WHERE memory_session_id = ? AND title = ? AND created_at_epoch = ?
680
+ `).get(e.memory_session_id,e.title,e.created_at_epoch);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(`
681
+ INSERT INTO observations (
682
+ memory_session_id, project, text, type, title, subtitle,
683
+ facts, narrative, concepts, files_read, files_modified,
684
+ prompt_number, discovery_tokens, agent_type, agent_id,
685
+ created_at, created_at_epoch
686
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
687
+ `).run(e.memory_session_id,e.project,e.text,e.type,e.title,e.subtitle,e.facts,e.narrative,e.concepts,e.files_read,e.files_modified,e.prompt_number,e.discovery_tokens||0,e.agent_type??null,e.agent_id??null,e.created_at,e.created_at_epoch).lastInsertRowid}}rebuildObservationsFTSIndex(){this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='observations_fts'").all().length>0&&this.db.run("INSERT INTO observations_fts(observations_fts) VALUES('rebuild')")}importUserPrompt(e){let t=this.db.prepare(`
688
+ SELECT id FROM user_prompts
689
+ WHERE content_session_id = ? AND prompt_number = ?
690
+ `).get(e.content_session_id,e.prompt_number);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(`
691
+ INSERT INTO user_prompts (
692
+ content_session_id, prompt_number, prompt_text,
693
+ created_at, created_at_epoch
694
+ ) VALUES (?, ?, ?, ?, ?)
695
+ `).run(e.content_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var I=require("fs"),k=require("path"),ae=require("os"),V=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,k.join)((0,ae.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,k.join)((0,ae.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static getBool(e){let t=this.get(e);return t==="true"||t===!0}static applyEnvOverrides(e){let t={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(t[s]=process.env[s]);return t}static loadFromFile(e){try{if(!(0,I.existsSync)(e)){let i=this.getAllDefaults();try{let a=(0,k.dirname)(e);(0,I.existsSync)(a)||(0,I.mkdirSync)(a,{recursive:!0}),(0,I.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,a instanceof Error?a.message:String(a))}return this.applyEnvOverrides(i)}let t=(0,I.readFileSync)(e,"utf-8"),s=JSON.parse(t),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{(0,I.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(i){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,i instanceof Error?i.message:String(i))}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(o[i]=n[i]);return this.applyEnvOverrides(o)}catch(t){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,t instanceof Error?t.message:String(t)),this.applyEnvOverrides(this.getAllDefaults())}}};var F=require("fs"),q=require("path");var C=class r{static instance=null;activeMode=null;modesDir;constructor(){let e=Le(),t=[(0,q.join)(e,"modes"),(0,q.join)(e,"..","plugin","modes")],s=t.find(n=>(0,F.existsSync)(n));this.modesDir=s||t[0]}static getInstance(){return r.instance||(r.instance=new r),r.instance}parseInheritance(e){let t=e.split("--");if(t.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(t.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:t[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,t){let s={...e};for(let n in t){let o=t[n],i=e[n];this.isPlainObject(o)&&this.isPlainObject(i)?s[n]=this.deepMerge(i,o):s[n]=o}return s}loadModeFile(e){let t=(0,q.join)(this.modesDir,`${e}.json`);if(!(0,F.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let s=(0,F.readFileSync)(t,"utf-8");return JSON.parse(s)}loadMode(e){let t=this.parseInheritance(e);if(!t.hasParent)try{let d=this.loadModeFile(e);return this.activeMode=d,u.debug("SYSTEM",`Loaded mode: ${d.name} (${e})`,void 0,{types:d.observation_types.map(l=>l.id),concepts:d.observation_concepts.map(l=>l.id)}),d}catch(d){if(d instanceof Error?u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:d.message}):u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(d)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:s,overrideId:n}=t,o;try{o=this.loadMode(s)}catch(d){d instanceof Error?u.warn("WORKER",`Parent mode '${s}' not found for ${e}, falling back to 'code'`,{message:d.message}):u.warn("WORKER",`Parent mode '${s}' not found for ${e}, falling back to 'code'`,{error:String(d)}),o=this.loadMode("code")}let i;try{i=this.loadModeFile(n),u.debug("SYSTEM",`Loaded override file: ${n} for parent ${s}`)}catch(d){return d instanceof Error?u.warn("WORKER",`Override file '${n}' not found, using parent mode '${s}' only`,{message:d.message}):u.warn("WORKER",`Override file '${n}' not found, using parent mode '${s}' only`,{error:String(d)}),this.activeMode=o,o}if(!i)return u.warn("SYSTEM",`Invalid override file: ${n}, using parent mode '${s}' only`),this.activeMode=o,o;let a=this.deepMerge(o,i);return this.activeMode=a,u.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${s} + ${n})`,void 0,{parent:s,override:n,types:a.observation_types.map(d=>d.id),concepts:a.observation_concepts.map(d=>d.id)}),a}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getObservationConcepts(){return this.getActiveMode().observation_concepts}getTypeIcon(e){return this.getObservationTypes().find(s=>s.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(s=>s.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(t=>t.id===e)}getTypeLabel(e){return this.getObservationTypes().find(s=>s.id===e)?.label||e}};function de(){let r=x.settings(),e=V.loadFromFile(r),t=C.getInstance().getActiveMode(),s=new Set(t.observation_types.map(o=>o.id)),n=new Set(t.observation_concepts.map(o=>o.id));return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:s,observationConcepts:n,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}var _={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},ke=4,_e=1;function ue(r){let e=(r.title?.length||0)+(r.subtitle?.length||0)+(r.narrative?.length||0)+JSON.stringify(r.facts||[]).length;return Math.ceil(e/ke)}function ce(r){let e=r.length,t=r.reduce((i,a)=>i+ue(a),0),s=r.reduce((i,a)=>i+(a.discovery_tokens||0),0),n=s-t,o=s>0?Math.round(n/s*100):0;return{totalObservations:e,totalReadTokens:t,totalDiscoveryTokens:s,savings:n,savingsPercent:o}}function es(r){return C.getInstance().getWorkEmoji(r)}function $(r,e){let t=ue(r),s=r.discovery_tokens||0,n=es(r.type),o=s>0?`${n} ${s.toLocaleString()}`:"-";return{readTokens:t,discoveryTokens:s,discoveryDisplay:o,workEmoji:n}}function Y(r){return r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent}var $e=U(require("path"),1),K=require("fs");var ts=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],rr=new RegExp(`<(${ts.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),Fe=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var ss=["task-notification"],nr=new RegExp(`^\\s*<(${ss.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),or=256*1024;function le(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(",");return r.db.prepare(`
696
+ SELECT
697
+ o.id,
698
+ o.memory_session_id,
699
+ COALESCE(s.platform_source, 'claude') as platform_source,
700
+ o.type,
701
+ o.title,
702
+ o.subtitle,
703
+ o.narrative,
704
+ o.facts,
705
+ o.concepts,
706
+ o.files_read,
707
+ o.files_modified,
708
+ o.discovery_tokens,
709
+ o.created_at,
710
+ o.created_at_epoch
711
+ FROM observations o
712
+ LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
713
+ WHERE (o.project = ? OR o.merged_into_project = ?)
714
+ AND type IN (${n})
715
+ AND EXISTS (
716
+ SELECT 1 FROM json_each(o.concepts)
717
+ WHERE value IN (${i})
718
+ )
719
+ ORDER BY o.created_at_epoch DESC
720
+ LIMIT ?
721
+ `).all(e,e,...s,...o,t.totalObservationCount)}function me(r,e,t){return r.db.prepare(`
722
+ SELECT
723
+ ss.id,
724
+ ss.memory_session_id,
725
+ COALESCE(s.platform_source, 'claude') as platform_source,
726
+ ss.request,
727
+ ss.investigated,
728
+ ss.learned,
729
+ ss.completed,
730
+ ss.next_steps,
731
+ ss.created_at,
732
+ ss.created_at_epoch
733
+ FROM session_summaries ss
734
+ LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
735
+ WHERE (ss.project = ? OR ss.merged_into_project = ?)
736
+ ORDER BY ss.created_at_epoch DESC
737
+ LIMIT ?
738
+ `).all(e,e,t.sessionCount+_e)}function Pe(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(","),a=e.map(()=>"?").join(",");return r.db.prepare(`
739
+ SELECT
740
+ o.id,
741
+ o.memory_session_id,
742
+ COALESCE(s.platform_source, 'claude') as platform_source,
743
+ o.type,
744
+ o.title,
745
+ o.subtitle,
746
+ o.narrative,
747
+ o.facts,
748
+ o.concepts,
749
+ o.files_read,
750
+ o.files_modified,
751
+ o.discovery_tokens,
752
+ o.created_at,
753
+ o.created_at_epoch,
754
+ o.project
755
+ FROM observations o
756
+ LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
757
+ WHERE (o.project IN (${a})
758
+ OR o.merged_into_project IN (${a}))
759
+ AND type IN (${n})
760
+ AND EXISTS (
761
+ SELECT 1 FROM json_each(o.concepts)
762
+ WHERE value IN (${i})
763
+ )
764
+ ORDER BY o.created_at_epoch DESC
765
+ LIMIT ?
766
+ `).all(...e,...e,...s,...o,t.totalObservationCount)}function He(r,e,t){let s=e.map(()=>"?").join(",");return r.db.prepare(`
767
+ SELECT
768
+ ss.id,
769
+ ss.memory_session_id,
770
+ COALESCE(s.platform_source, 'claude') as platform_source,
771
+ ss.request,
772
+ ss.investigated,
773
+ ss.learned,
774
+ ss.completed,
775
+ ss.next_steps,
776
+ ss.created_at,
777
+ ss.created_at_epoch,
778
+ ss.project
779
+ FROM session_summaries ss
780
+ LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
781
+ WHERE (ss.project IN (${s})
782
+ OR ss.merged_into_project IN (${s}))
783
+ ORDER BY ss.created_at_epoch DESC
784
+ LIMIT ?
785
+ `).all(...e,...e,t.sessionCount+_e)}function Ge(r){return r.replace(/[/.]/g,"-")}function rs(r){if(!r.includes('"type":"assistant"'))return null;let e=JSON.parse(r);if(e.type==="assistant"&&e.message?.content&&Array.isArray(e.message.content)){let t="";for(let s of e.message.content)s.type==="text"&&(t+=s.text);if(t=t.replace(Fe,"").trim(),t)return t}return null}function ns(r){for(let e=r.length-1;e>=0;e--)try{let t=rs(r[e]);if(t)return t}catch(t){t instanceof Error?u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e},t):u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e,error:String(t)});continue}return""}function os(r){try{if(!(0,K.existsSync)(r))return{userMessage:"",assistantMessage:""};let e=(0,K.readFileSync)(r,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(`
786
+ `).filter(n=>n.trim());return{userMessage:"",assistantMessage:ns(t)}}catch(e){return e instanceof Error?u.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e):u.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r,error:String(e)}),{userMessage:"",assistantMessage:""}}}function pe(r,e,t,s){if(!e.showLastMessage||r.length===0)return{userMessage:"",assistantMessage:""};let n=r.find(d=>d.memory_session_id!==t);if(!n)return{userMessage:"",assistantMessage:""};let o=n.memory_session_id,i=Ge(s),a=$e.default.join(v,"projects",i,`${o}.jsonl`);return os(a)}function je(r,e){let t=e[0]?.id;return r.map((s,n)=>{let o=n===0?null:e[n+1];return{...s,displayEpoch:o?o.created_at_epoch:s.created_at_epoch,displayTime:o?o.created_at:s.created_at,shouldShowLink:s.id!==t}})}function Ee(r,e){let t=[...r.map(s=>({type:"observation",data:s})),...e.map(s=>({type:"summary",data:s}))];return t.sort((s,n)=>{let o=s.type==="observation"?s.data.created_at_epoch:s.data.displayEpoch,i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch;return o-i}),t}function Xe(r,e){return new Set(r.slice(0,e).map(t=>t.id))}function Be(){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 We(r){return[`# [${r}] recent context, ${Be()}`,""]}function Ve(){return[`Legend: \u{1F3AF}session ${C.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji}${t.id}`).join(" ")}`,"Format: ID TIME TYPE TITLE","Fetch details: get_observations([IDs]) | Search: mem-search skill",""]}function qe(){return[]}function Ye(){return[]}function Ke(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 Je(r){return[`### ${r}`]}function Qe(r){return r.toLowerCase().replace(" am","a").replace(" pm","p")}function ze(r,e,t){let s=r.title||"Untitled",n=C.getInstance().getTypeIcon(r.type),o=e?Qe(e):'"';return`${r.id} ${o} ${n} ${s}`}function Ze(r,e,t,s){let n=[],o=r.title||"Untitled",i=C.getInstance().getTypeIcon(r.type),a=e?Qe(e):'"',{readTokens:d,discoveryDisplay:l}=$(r,s);n.push(`**${r.id}** ${a} ${i} **${o}**`),t&&n.push(t);let c=[];return s.showReadTokens&&c.push(`~${d}t`),s.showWorkTokens&&c.push(l),c.length>0&&n.push(c.join(" ")),n.push(""),n}function et(r,e){return[`S${r.id} ${r.request||"Session started"} (${e})`]}function P(r,e){return e?[`**${r}**: ${e}`,""]:[]}function tt(r){return r.assistantMessage?["","---","","**Previously**","",`A: ${r.assistantMessage}`,""]:[]}function st(r,e){return["",`Access ${Math.round(r/1e3)}k tokens of past work via get_observations([IDs]) or mem-search skill.`]}function rt(r){return`# [${r}] recent context, ${Be()}
787
+
788
+ No previous sessions found.`}function nt(){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 ot(r){return["",`${_.bright}${_.cyan}[${r}] recent context, ${nt()}${_.reset}`,`${_.gray}${"\u2500".repeat(60)}${_.reset}`,""]}function it(){let e=C.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ");return[`${_.dim}Legend: session-request | ${e}${_.reset}`,""]}function at(){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 dt(){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 _t(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 ut(r){return[`${_.bright}${_.cyan}${r}${_.reset}`,""]}function ct(r){return[`${_.dim}${r}${_.reset}`]}function lt(r,e,t,s){let n=r.title||"Untitled",o=C.getInstance().getTypeIcon(r.type),{readTokens:i,discoveryTokens:a,workEmoji:d}=$(r,s),l=t?`${_.dim}${e}${_.reset}`:" ".repeat(e.length),c=s.showReadTokens&&i>0?`${_.dim}(~${i}t)${_.reset}`:"",T=s.showWorkTokens&&a>0?`${_.dim}(${d} ${a.toLocaleString()}t)${_.reset}`:"";return` ${_.dim}#${r.id}${_.reset} ${l} ${o} ${n} ${c} ${T}`}function mt(r,e,t,s,n){let o=[],i=r.title||"Untitled",a=C.getInstance().getTypeIcon(r.type),{readTokens:d,discoveryTokens:l,workEmoji:c}=$(r,n),T=t?`${_.dim}${e}${_.reset}`:" ".repeat(e.length),p=n.showReadTokens&&d>0?`${_.dim}(~${d}t)${_.reset}`:"",E=n.showWorkTokens&&l>0?`${_.dim}(${c} ${l.toLocaleString()}t)${_.reset}`:"";return o.push(` ${_.dim}#${r.id}${_.reset} ${T} ${a} ${_.bright}${i}${_.reset}`),s&&o.push(` ${_.dim}${s}${_.reset}`),(p||E)&&o.push(` ${p} ${E}`),o.push(""),o}function pt(r,e){let t=`${r.request||"Session started"} (${e})`;return[`${_.yellow}#S${r.id}${_.reset} ${t}`,""]}function H(r,e,t){return e?[`${t}${r}:${_.reset} ${e}`,""]:[]}function Et(r){return r.assistantMessage?["","---","",`${_.bright}${_.magenta}Previously${_.reset}`,"",`${_.dim}A: ${r.assistantMessage}${_.reset}`,""]:[]}function gt(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`
789
+ ${_.bright}${_.cyan}[${r}] recent context, ${nt()}${_.reset}
790
+ ${_.gray}${"\u2500".repeat(60)}${_.reset}
791
+
792
+ ${_.dim}No previous sessions found for this project yet.${_.reset}
793
+ `}function ft(r,e,t,s){let n=[];return s?n.push(...ot(r)):n.push(...We(r)),s?n.push(...it()):n.push(...Ve()),s?n.push(...at()):n.push(...qe()),s?n.push(...dt()):n.push(...Ye()),Y(t)&&(s?n.push(..._t(e,t)):n.push(...Ke(e,t))),n}var ge=U(require("path"),1);function z(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return u.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e instanceof Error?e:new Error(String(e))),[]}}function Te(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function fe(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function bt(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function St(r,e){return ge.default.isAbsolute(r)?ge.default.relative(e,r):r}function ht(r,e,t){let s=z(r);if(s.length>0)return St(s[0],e);if(t){let n=z(t);if(n.length>0)return St(n[0],e)}return"General"}function is(r){let e=new Map;for(let s of r){let n=s.type==="observation"?s.data.created_at:s.data.displayTime,o=bt(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 Ot(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?z(r.facts).join(`
794
+ `):null}function as(r,e,t,s){let n=[];n.push(...Je(r));let o="";for(let i of e)if(i.type==="summary"){let a=i.data,d=Te(a.displayTime);n.push(...et(a,d))}else{let a=i.data,d=fe(a.created_at),c=d!==o?d:"";if(o=d,t.has(a.id)){let p=Ot(a,s);n.push(...Ze(a,c,p,s))}else n.push(ze(a,c,s))}return n}function ds(r,e,t,s,n){let o=[];o.push(...ut(r));let i=null,a="";for(let d of e)if(d.type==="summary"){i=null,a="";let l=d.data,c=Te(l.displayTime);o.push(...pt(l,c))}else{let l=d.data,c=ht(l.files_modified,n,l.files_read),T=fe(l.created_at),p=T!==a;a=T;let E=t.has(l.id);if(c!==i&&(o.push(...ct(c)),i=c),E){let f=Ot(l,s);o.push(...mt(l,T,p,f,s))}else o.push(lt(l,T,p,s))}return o.push(""),o}function _s(r,e,t,s,n,o){return o?ds(r,e,t,s,n):as(r,e,t,s)}function Rt(r,e,t,s,n){let o=[],i=is(r);for(let[a,d]of i)o.push(..._s(a,d,e,t,s,n));return o}function At(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 Nt(r,e){let t=[];return e?(t.push(...H("Investigated",r.investigated,_.blue)),t.push(...H("Learned",r.learned,_.yellow)),t.push(...H("Completed",r.completed,_.green)),t.push(...H("Next Steps",r.next_steps,_.magenta))):(t.push(...P("Investigated",r.investigated)),t.push(...P("Learned",r.learned)),t.push(...P("Completed",r.completed)),t.push(...P("Next Steps",r.next_steps))),t}function Ct(r,e){return e?Et(r):tt(r)}function It(r,e,t){return!Y(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?gt(r.totalDiscoveryTokens,r.totalReadTokens):st(r.totalDiscoveryTokens,r.totalReadTokens)}var us=Lt.default.join((0,Mt.homedir)(),".claude","plugins","marketplaces","bjlee2024","plugin",".install-version");function cs(){try{return new W}catch(r){if(r instanceof Error&&r.code==="ERR_DLOPEN_FAILED"){try{(0,Dt.unlinkSync)(us)}catch(e){e instanceof Error?u.debug("WORKER","Marker file cleanup failed (may not exist)",{},e):u.debug("WORKER","Marker file cleanup failed (may not exist)",{error:String(e)})}return u.error("WORKER","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function ls(r,e){return e?Tt(r):rt(r)}function ms(r,e,t,s,n,o,i){let a=[],d=ce(e);a.push(...ft(r,d,s,i));let l=t.slice(0,s.sessionCount),c=je(l,t),T=Ee(e,c),p=Xe(e,s.fullObservationCount);a.push(...Rt(T,p,s,n,i));let E=t[0],f=e[0];At(s,E,f)&&a.push(...Nt(E,i));let b=pe(e,s,o,n);return a.push(...Ct(b,i)),a.push(...It(d,s,i)),a.join(`
795
+ `).trimEnd()}async function Se(r,e=!1){let t=de(),s=r?.cwd??process.cwd(),n=ne(s),o=r?.projects?.length?r.projects:n.allProjects,i=o[o.length-1]??n.primary;r?.full&&(t.totalObservationCount=999999,t.sessionCount=999999);let a=cs();if(!a)return"";try{let d=o.length>1?Pe(a,o,t):le(a,i,t),l=o.length>1?He(a,o,t):me(a,i,t);return d.length===0&&l.length===0?ls(i,e):ms(i,d,l,t,s,r?.session_id,e)}finally{a.close()}}0&&(module.exports={generateContext});