@kykiles/opencode-mem 13.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +429 -0
  3. package/dist/npx-cli/index.js +9798 -0
  4. package/dist/opencode-plugin/index.js +70 -0
  5. package/package.json +187 -0
  6. package/plugin/.mcp.json +12 -0
  7. package/plugin/bun.lock +160 -0
  8. package/plugin/hooks/bugfixes-2026-01-10.md +92 -0
  9. package/plugin/hooks/hooks.json +87 -0
  10. package/plugin/modes/code--ar.json +24 -0
  11. package/plugin/modes/code--bn.json +24 -0
  12. package/plugin/modes/code--chill.json +8 -0
  13. package/plugin/modes/code--cs.json +24 -0
  14. package/plugin/modes/code--da.json +24 -0
  15. package/plugin/modes/code--de.json +24 -0
  16. package/plugin/modes/code--el.json +24 -0
  17. package/plugin/modes/code--es.json +24 -0
  18. package/plugin/modes/code--fi.json +24 -0
  19. package/plugin/modes/code--fr.json +24 -0
  20. package/plugin/modes/code--he.json +24 -0
  21. package/plugin/modes/code--hi.json +24 -0
  22. package/plugin/modes/code--hu.json +24 -0
  23. package/plugin/modes/code--id.json +24 -0
  24. package/plugin/modes/code--it.json +24 -0
  25. package/plugin/modes/code--ja.json +24 -0
  26. package/plugin/modes/code--ko.json +24 -0
  27. package/plugin/modes/code--nl.json +24 -0
  28. package/plugin/modes/code--no.json +24 -0
  29. package/plugin/modes/code--pl.json +24 -0
  30. package/plugin/modes/code--pt-br.json +24 -0
  31. package/plugin/modes/code--ro.json +24 -0
  32. package/plugin/modes/code--ru.json +24 -0
  33. package/plugin/modes/code--sv.json +24 -0
  34. package/plugin/modes/code--th.json +24 -0
  35. package/plugin/modes/code--tr.json +24 -0
  36. package/plugin/modes/code--uk.json +24 -0
  37. package/plugin/modes/code--ur.json +25 -0
  38. package/plugin/modes/code--vi.json +24 -0
  39. package/plugin/modes/code--zh.json +24 -0
  40. package/plugin/modes/code.json +139 -0
  41. package/plugin/modes/email-investigation.json +120 -0
  42. package/plugin/modes/law-study--chill.json +7 -0
  43. package/plugin/modes/law-study-CLAUDE.md +85 -0
  44. package/plugin/modes/law-study.json +120 -0
  45. package/plugin/modes/meme-tokens.json +125 -0
  46. package/plugin/package.json +45 -0
  47. package/plugin/scripts/bun-runner.js +238 -0
  48. package/plugin/scripts/context-generator.cjs +825 -0
  49. package/plugin/scripts/mcp-server.cjs +249 -0
  50. package/plugin/scripts/server-service.cjs +9939 -0
  51. package/plugin/scripts/statusline-counts.js +40 -0
  52. package/plugin/scripts/transcript-watcher.cjs +29 -0
  53. package/plugin/scripts/version-check.js +193 -0
  54. package/plugin/scripts/worker-service.cjs +2238 -0
  55. package/plugin/scripts/worker-wrapper.cjs +2 -0
  56. package/plugin/skills/babysit/SKILL.md +87 -0
  57. package/plugin/skills/design-is/SKILL.md +312 -0
  58. package/plugin/skills/do/SKILL.md +45 -0
  59. package/plugin/skills/how-it-works/SKILL.md +22 -0
  60. package/plugin/skills/how-it-works/onboarding-explainer.md +17 -0
  61. package/plugin/skills/knowledge-agent/SKILL.md +80 -0
  62. package/plugin/skills/learn-codebase/SKILL.md +21 -0
  63. package/plugin/skills/make-plan/SKILL.md +67 -0
  64. package/plugin/skills/mem-search/SKILL.md +131 -0
  65. package/plugin/skills/oh-my-issues/SKILL.md +226 -0
  66. package/plugin/skills/pathfinder/SKILL.md +111 -0
  67. package/plugin/skills/smart-explore/SKILL.md +193 -0
  68. package/plugin/skills/standup/SKILL.md +142 -0
  69. package/plugin/skills/standup/agent-brief.md +47 -0
  70. package/plugin/skills/standup/standup.mjs +662 -0
  71. package/plugin/skills/timeline-report/SKILL.md +211 -0
  72. package/plugin/skills/version-bump/SKILL.md +74 -0
  73. package/plugin/skills/version-bump/scripts/generate_changelog.js +34 -0
  74. package/plugin/skills/weekly-digests/SKILL.md +262 -0
  75. package/plugin/skills/what-the/SKILL.md +6 -0
  76. package/plugin/skills/wowerpoint/SKILL.md +205 -0
  77. package/plugin/sqlite/SessionStore.js +764 -0
  78. package/plugin/sqlite/observations/files.js +10 -0
  79. package/plugin/ui/assets/fonts/monaspace-radon-var.woff +0 -0
  80. package/plugin/ui/assets/fonts/monaspace-radon-var.woff2 +0 -0
  81. package/plugin/ui/claude-mem-logo-for-dark-mode.webp +0 -0
  82. package/plugin/ui/claude-mem-logo-stylized.png +0 -0
  83. package/plugin/ui/claude-mem-logomark.webp +0 -0
  84. package/plugin/ui/icon-thick-completed.svg +8 -0
  85. package/plugin/ui/icon-thick-investigated.svg +8 -0
  86. package/plugin/ui/icon-thick-learned.svg +12 -0
  87. package/plugin/ui/icon-thick-next-steps.svg +8 -0
  88. package/plugin/ui/viewer-bundle.js +65 -0
  89. package/plugin/ui/viewer.html +2402 -0
@@ -0,0 +1,764 @@
1
+ var __IMPORT_META_URL__ = require("node:url").pathToFileURL(__filename).href;
2
+ "use strict";var w=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var ie=Object.prototype.hasOwnProperty;var ae=(a,e)=>{for(var t in e)w(a,t,{get:e[t],enumerable:!0})},de=(a,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of oe(e))!ie.call(a,r)&&r!==t&&w(a,r,{get:()=>e[r],enumerable:!(s=ne(e,r))||s.enumerable});return a};var _e=a=>de(w({},"__esModule",{value:!0}),a);var fe={};ae(fe,{SessionStore:()=>j});module.exports=_e(fe);var H=require("bun:sqlite");var S=require("path"),x=require("os"),D=require("fs"),W=require("url");var pe=null;function Ee(a){return(pe??process.stderr.write.bind(process.stderr))(a)}function U(a){Ee(a)}var ve=process.platform==="win32";function ue(a){return a.replace(/^\uFEFF/,"")}function M(a){return JSON.parse(ue(a))}function me(){return typeof __dirname<"u"?__dirname:(0,S.dirname)((0,W.fileURLToPath)(__IMPORT_META_URL__))}var Me=me();function le(){if(process.env.OPENCODE_MEM_DATA_DIR)return process.env.OPENCODE_MEM_DATA_DIR;let a=(0,S.join)((0,x.homedir)(),".opencode-mem"),e=(0,S.join)(a,"settings.json");try{if((0,D.existsSync)(e)){let t=M((0,D.readFileSync)(e,"utf-8")),s=t.env??t;if(s.OPENCODE_MEM_DATA_DIR)return s.OPENCODE_MEM_DATA_DIR}}catch{}return a}var g=le(),ce=process.env.CLAUDE_CONFIG_DIR||(0,S.join)((0,x.homedir)(),".claude"),Fe=(0,S.join)(ce,"plugins","marketplaces","thedotmack"),Te=(0,S.join)(g,"logs"),we=(0,S.join)(g,"settings.json"),q=(0,S.join)(g,"opencode-mem.db"),be=(0,S.join)(g,"observer-sessions"),k=(0,S.basename)(be);function V(a){(0,D.mkdirSync)(a,{recursive:!0})}var X={dataDir:()=>g,workerPid:()=>(0,S.join)(g,"worker.pid"),serverPid:()=>(0,S.join)(g,".server-beta.pid"),serverPort:()=>(0,S.join)(g,".server-beta.port"),serverRuntime:()=>(0,S.join)(g,".server-beta.runtime.json"),settings:()=>(0,S.join)(g,"settings.json"),database:()=>(0,S.join)(g,"opencode-mem.db"),chroma:()=>(0,S.join)(g,"chroma"),combinedCerts:()=>(0,S.join)(g,"combined_certs.pem"),transcriptsConfig:()=>(0,S.join)(g,"transcript-watch.json"),transcriptsState:()=>(0,S.join)(g,"transcript-watch-state.json"),corpora:()=>(0,S.join)(g,"corpora"),supervisorRegistry:()=>(0,S.join)(g,"supervisor.json"),envFile:()=>(0,S.join)(g,".env"),logsDir:()=>Te};var C=require("fs"),Y=require("path");var G=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(G||{}),P=null,B=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,C.existsSync)(e)||(0,C.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,Y.join)(e,`opencode-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,C.existsSync)(e)){let t=(0,C.readFileSync)(e,"utf-8"),r=(M(t).OPENCODE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=G[r]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
3
+ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let s=t;if(typeof t=="string")try{s=JSON.parse(t)}catch{s=t}if(e==="Bash"&&s.command)return`${e}(${s.command})`;if(s.file_path)return`${e}(${s.file_path})`;if(s.notebook_path)return`${e}(${s.notebook_path})`;if(e==="Glob"&&s.pattern)return`${e}(${s.pattern})`;if(e==="Grep"&&s.pattern)return`${e}(${s.pattern})`;if(s.url)return`${e}(${s.url})`;if(s.query)return`${e}(${s.query})`;if(e==="Task"){if(s.subagent_type)return`${e}(${s.subagent_type})`;if(s.description)return`${e}(${s.description})`}return e==="Skill"&&s.skill?`${e}(${s.skill})`:e==="LSP"&&s.operation?`${e}(${s.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),i=String(e.getSeconds()).padStart(2,"0"),p=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${s}-${r} ${n}:${o}:${i}.${p}`}log(e,t,s,r,n){if(e<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),i=G[e].padEnd(5),p=t.padEnd(6),_="";r?.correlationId?_=`[${r.correlationId}] `:r?.sessionId&&(_=`[session-${r.sessionId}] `);let u="";if(n!=null)if(n instanceof Error)u=this.getLevel()===0?`
4
+ ${n.message}
5
+ ${n.stack}`:` ${n.message}`;else if(this.getLevel()===0&&typeof n=="object")try{u=`
6
+ `+JSON.stringify(n,null,2)}catch{u=" "+this.formatData(n)}else u=" "+this.formatData(n);let I="";if(r){let{sessionId:N,memorySessionId:O,correlationId:R,...m}=r;Object.keys(m).length>0&&(I=` {${Object.entries(m).map(([f,v])=>`${f}=${v}`).join(", ")}}`)}let c=`[${o}] [${i}] [${p}] ${_}${s}${I}${u}`;if(this.logFilePath)try{(0,C.appendFileSync)(this.logFilePath,c+`
7
+ `,"utf8")}catch(N){let O=N instanceof Error?N:new Error(String(N));U(`[LOGGER] Failed to write to log file: ${O.message}
8
+ ${O.stack??""}
9
+ `)}else U(c+`
10
+ `)}debug(e,t,s,r){this.log(0,e,t,s,r)}info(e,t,s,r){this.log(1,e,t,s,r)}warn(e,t,s,r){this.log(2,e,t,s,r)}setErrorSink(e){P=e}error(e,t,s,r){this.log(3,e,t,s,r),this.routeErrorToSink(t,s,r)}routeErrorToSink(e,t,s){try{if(!P||!(s instanceof Error))return;P(s)}catch{}}dataIn(e,t,s,r){this.info(e,`\u2192 ${t}`,s,r)}dataOut(e,t,s,r){this.info(e,`\u2190 ${t}`,s,r)}success(e,t,s,r){this.info(e,`\u2713 ${t}`,s,r)}failure(e,t,s,r){this.error(e,`\u2717 ${t}`,s,r)}},d=new B;var K=require("crypto");function Q(a,e,t){return(0,K.createHash)("sha256").update([a||"",e||"",t||""].join("\0")).digest("hex").slice(0,16)}var E="claude";function Se(a){return a.trim().toLowerCase().replace(/\s+/g,"-")}function L(a){if(!a)return E;let e=Se(a);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:E}function J(a){let e=["claude","codex","cursor"];return[...a].sort((t,s)=>{let r=e.indexOf(t),n=e.indexOf(s);return r!==-1||n!==-1?r===-1?1:n===-1?-1:r-n:t.localeCompare(s)})}function z(a,e,t,s,r){let n=Date.now()-s,o=r!==void 0?"up.session_db_id = ?":"up.content_session_id = ?",i=r??e;return a.prepare(`
11
+ SELECT
12
+ up.*,
13
+ s.memory_session_id,
14
+ s.project,
15
+ COALESCE(s.platform_source, '${E}') as platform_source
16
+ FROM user_prompts up
17
+ JOIN sdk_sessions s ON up.session_db_id = s.id
18
+ WHERE ${o}
19
+ AND up.prompt_text = ?
20
+ AND up.created_at_epoch >= ?
21
+ ORDER BY up.created_at_epoch DESC
22
+ LIMIT 1
23
+ `).get(i,t,n)??void 0}var se=["private","opencode-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Z=new RegExp(`<(${se.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var ee=100;function Re(a){let e=Object.fromEntries(se.map(r=>[r,0]));Z.lastIndex=0;let t=0,s=a.replace(Z,(r,n)=>(e[n]=(e[n]??0)+1,t+=1,""));return t>ee&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:ee,contentLength:a.length}),{stripped:s.trim(),counts:e}}function te(a){return Re(a).stripped}var Ne=["task-notification"],qe=new RegExp(`^\\s*<(${Ne.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Ve=256*1024;var $=4e3;function F(a){let e=a.trim(),s=te(a).trim()||e;return s.length<=$?s:(d.debug("DB","Truncated stored prompt text to the configured cap",{originalLength:s.length,storedLength:$}),`${s.slice(0,$-1)}\u2026`)}var Ie=require("bun:sqlite");var he=5e3,ge=4194304;function Oe(a){return a.prepare(`
24
+ SELECT name
25
+ FROM sqlite_master
26
+ WHERE type = 'table'
27
+ AND name NOT LIKE 'sqlite_%'
28
+ LIMIT 1
29
+ `).get()!=null}function y(a,e,t){try{a.run(e)}catch(s){let r=s instanceof Error?s:new Error(String(s));throw d.warn("DB",`Failed to apply SQLite pragma ${t}`,{sql:e},r),s}}function re(a,e={}){let{enableWal:t=!0,enableIncrementalAutoVacuum:s=!0}=e;y(a,`PRAGMA busy_timeout = ${he}`,"busy_timeout"),y(a,"PRAGMA foreign_keys = ON","foreign_keys"),y(a,"PRAGMA synchronous = NORMAL","synchronous"),y(a,`PRAGMA journal_size_limit = ${ge}`,"journal_size_limit"),s&&!Oe(a)&&y(a,"PRAGMA auto_vacuum = INCREMENTAL","auto_vacuum"),t&&y(a,"PRAGMA journal_mode = WAL","journal_mode")}var j=class{db;constructor(e=q){e instanceof H.Database?this.db=e:(e!==":memory:"&&V(g),this.db=new H.Database(e)),re(this.db),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable(),this.ensureDiscoveryTokensColumn(),this.createPendingMessagesTable(),this.renameSessionIdColumns(),this.addFailedAtEpochColumn(),this.addOnUpdateCascadeToForeignKeys(),this.addObservationContentHashColumn(),this.addSessionCustomTitleColumn(),this.addSessionPlatformSourceColumn(),this.addObservationModelColumns(),this.ensureMergedIntoProjectColumns(),this.addObservationSubagentColumns(),this.addObservationsUniqueContentHashIndex(),this.addObservationsMetadataColumn(),this.dropDeadPendingMessagesColumns(),this.ensurePendingMessagesToolUseIdColumn(),this.dropWorkerPidColumn(),this.ensureSDKSessionsPlatformContentIdentity(),this.ensureUserPromptsSessionDbId(),this.ensurePendingMessagesSessionToolUniqueIndex()}getIndexColumns(e){return this.db.query(`PRAGMA index_info(${JSON.stringify(e)})`).all().map(t=>t.name)}hasUniqueIndexOnColumns(e,t){return this.db.query(`PRAGMA index_list(${e})`).all().some(r=>{if(r.unique!==1)return!1;let n=this.getIndexColumns(r.name);return n.length===t.length&&n.every((o,i)=>o===t[i])})}resolvePromptSessionDbId(e,t,s){if(t!==void 0)return t;let r=s?L(s):void 0;return r?this.db.prepare(`
30
+ SELECT id
31
+ FROM sdk_sessions
32
+ WHERE COALESCE(NULLIF(platform_source, ''), ?) = ?
33
+ AND content_session_id = ?
34
+ LIMIT 1
35
+ `).get(E,r,e)?.id??null:this.db.prepare(`
36
+ SELECT id
37
+ FROM sdk_sessions
38
+ WHERE content_session_id = ?
39
+ ORDER BY CASE COALESCE(NULLIF(platform_source, ''), '${E}')
40
+ WHEN '${E}' THEN 0
41
+ ELSE 1
42
+ END, id
43
+ LIMIT 1
44
+ `).get(e)?.id??null}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(r=>r.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"),d.debug("DB","Dropped worker_pid column and its index from pending_messages")}catch(r){d.warn("DB","Failed to drop worker_pid column from pending_messages",{},r instanceof Error?r:new Error(String(r)));return}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(32,new Date().toISOString())}}ensureSDKSessionsPlatformContentIdentity(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(33),t=this.hasUniqueIndexOnColumns("sdk_sessions",["content_session_id"]),s=this.hasUniqueIndexOnColumns("sdk_sessions",["platform_source","content_session_id"]),n=this.db.query("PRAGMA table_info(sdk_sessions)").all().some(o=>o.name==="platform_source");if(!(e&&!t&&s&&n)){if(n||this.db.run(`ALTER TABLE sdk_sessions ADD COLUMN platform_source TEXT NOT NULL DEFAULT '${E}'`),this.db.run(`
45
+ UPDATE sdk_sessions
46
+ SET platform_source = '${E}'
47
+ WHERE platform_source IS NULL OR platform_source = ''
48
+ `),t){this.db.run("PRAGMA foreign_keys = OFF"),this.db.run("BEGIN TRANSACTION");try{this.rebuildSdkSessionsWithCompositeIdentity(e),this.db.run("COMMIT")}catch(o){this.db.run("ROLLBACK");let i=o instanceof Error?o:new Error(String(o));throw d.error("DB","Failed to rebuild sdk_sessions with composite identity, rolled back",{},i),o}finally{this.db.run("PRAGMA foreign_keys = ON")}return}this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS ux_sdk_sessions_platform_content ON sdk_sessions(platform_source, content_session_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_sdk_sessions_platform_source ON sdk_sessions(platform_source)"),e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(33,new Date().toISOString())}}rebuildSdkSessionsWithCompositeIdentity(e){this.db.run("DROP TABLE IF EXISTS sdk_sessions_new"),this.db.run(`
49
+ CREATE TABLE sdk_sessions_new (
50
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
51
+ content_session_id TEXT NOT NULL,
52
+ memory_session_id TEXT UNIQUE,
53
+ project TEXT NOT NULL,
54
+ platform_source TEXT NOT NULL DEFAULT '${E}',
55
+ user_prompt TEXT,
56
+ started_at TEXT NOT NULL,
57
+ started_at_epoch INTEGER NOT NULL,
58
+ completed_at TEXT,
59
+ completed_at_epoch INTEGER,
60
+ status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'completed', 'failed')),
61
+ worker_port INTEGER,
62
+ prompt_counter INTEGER DEFAULT 0,
63
+ custom_title TEXT
64
+ )
65
+ `),this.db.run(`
66
+ INSERT INTO sdk_sessions_new (
67
+ id, content_session_id, memory_session_id, project, platform_source,
68
+ user_prompt, started_at, started_at_epoch, completed_at, completed_at_epoch,
69
+ status, worker_port, prompt_counter, custom_title
70
+ )
71
+ SELECT
72
+ id, content_session_id, memory_session_id, project,
73
+ COALESCE(NULLIF(platform_source, ''), '${E}'),
74
+ user_prompt, started_at, started_at_epoch, completed_at, completed_at_epoch,
75
+ status, worker_port, prompt_counter, custom_title
76
+ FROM sdk_sessions
77
+ `),this.db.run("DROP TABLE sdk_sessions"),this.db.run("ALTER TABLE sdk_sessions_new RENAME TO sdk_sessions"),this.db.run("CREATE INDEX IF NOT EXISTS idx_sdk_sessions_claude_id ON sdk_sessions(content_session_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_sdk_sessions_sdk_id ON sdk_sessions(memory_session_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_sdk_sessions_project ON sdk_sessions(project)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_sdk_sessions_status ON sdk_sessions(status)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_sdk_sessions_started ON sdk_sessions(started_at_epoch DESC)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_sdk_sessions_platform_source ON sdk_sessions(platform_source)"),this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS ux_sdk_sessions_platform_content ON sdk_sessions(platform_source, content_session_id)"),e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(33,new Date().toISOString())}ensureUserPromptsSessionDbId(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(34);if(this.db.query("SELECT name FROM sqlite_master WHERE type='table' AND name='user_prompts'").all().length===0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(34,new Date().toISOString());return}let r=this.db.query("PRAGMA table_info(user_prompts)").all().some(_=>_.name==="session_db_id"),o=this.db.query("PRAGMA foreign_key_list(user_prompts)").all().some(_=>_.table==="sdk_sessions"&&_.from==="content_session_id");if(e&&r&&!o)return;let i=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='user_prompts_fts'").all().length>0,p=r?`COALESCE(up.session_db_id, (
78
+ SELECT s.id FROM sdk_sessions s
79
+ WHERE s.content_session_id = up.content_session_id
80
+ ORDER BY CASE COALESCE(NULLIF(s.platform_source, ''), '${E}')
81
+ WHEN '${E}' THEN 0
82
+ ELSE 1
83
+ END, s.id
84
+ LIMIT 1
85
+ ))`:`(
86
+ SELECT s.id FROM sdk_sessions s
87
+ WHERE s.content_session_id = up.content_session_id
88
+ ORDER BY CASE COALESCE(NULLIF(s.platform_source, ''), '${E}')
89
+ WHEN '${E}' THEN 0
90
+ ELSE 1
91
+ END, s.id
92
+ LIMIT 1
93
+ )`;this.db.run("PRAGMA foreign_keys = OFF"),this.db.run("BEGIN TRANSACTION");try{this.rebuildUserPromptsWithSessionDbId(e,p,i),this.db.run("COMMIT")}catch(_){this.db.run("ROLLBACK");let u=_ instanceof Error?_:new Error(String(_));throw d.error("DB","Failed to rebuild user_prompts with session_db_id, rolled back",{},u),_}finally{this.db.run("PRAGMA foreign_keys = ON")}}rebuildUserPromptsWithSessionDbId(e,t,s){this.db.run("DROP TRIGGER IF EXISTS user_prompts_ai"),this.db.run("DROP TRIGGER IF EXISTS user_prompts_ad"),this.db.run("DROP TRIGGER IF EXISTS user_prompts_au"),this.db.run("DROP TABLE IF EXISTS user_prompts_new"),this.db.run(`
94
+ CREATE TABLE user_prompts_new (
95
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
96
+ session_db_id INTEGER,
97
+ content_session_id TEXT NOT NULL,
98
+ prompt_number INTEGER NOT NULL,
99
+ prompt_text TEXT NOT NULL,
100
+ created_at TEXT NOT NULL,
101
+ created_at_epoch INTEGER NOT NULL,
102
+ FOREIGN KEY(session_db_id) REFERENCES sdk_sessions(id) ON DELETE CASCADE
103
+ )
104
+ `),this.db.run(`
105
+ INSERT INTO user_prompts_new (
106
+ id, session_db_id, content_session_id, prompt_number,
107
+ prompt_text, created_at, created_at_epoch
108
+ )
109
+ SELECT
110
+ up.id,
111
+ ${t},
112
+ up.content_session_id,
113
+ up.prompt_number,
114
+ up.prompt_text,
115
+ up.created_at,
116
+ up.created_at_epoch
117
+ FROM user_prompts up
118
+ `),this.db.run("DROP TABLE user_prompts"),this.db.run("ALTER TABLE user_prompts_new RENAME TO user_prompts"),this.db.run("CREATE INDEX IF NOT EXISTS idx_user_prompts_session ON user_prompts(session_db_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_user_prompts_claude_session ON user_prompts(content_session_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_user_prompts_created ON user_prompts(created_at_epoch DESC)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_user_prompts_prompt_number ON user_prompts(prompt_number)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_user_prompts_lookup ON user_prompts(session_db_id, prompt_number)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_user_prompts_content_lookup ON user_prompts(content_session_id, prompt_number)"),s&&(this.db.run(`
119
+ CREATE TRIGGER user_prompts_ai AFTER INSERT ON user_prompts BEGIN
120
+ INSERT INTO user_prompts_fts(rowid, prompt_text)
121
+ VALUES (new.id, new.prompt_text);
122
+ END;
123
+
124
+ CREATE TRIGGER user_prompts_ad AFTER DELETE ON user_prompts BEGIN
125
+ INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text)
126
+ VALUES('delete', old.id, old.prompt_text);
127
+ END;
128
+
129
+ CREATE TRIGGER user_prompts_au AFTER UPDATE ON user_prompts BEGIN
130
+ INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text)
131
+ VALUES('delete', old.id, old.prompt_text);
132
+ INSERT INTO user_prompts_fts(rowid, prompt_text)
133
+ VALUES (new.id, new.prompt_text);
134
+ END;
135
+ `),this.db.run("INSERT INTO user_prompts_fts(user_prompts_fts) VALUES('rebuild')")),e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(34,new Date().toISOString())}ensurePendingMessagesSessionToolUniqueIndex(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(35);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(35,new Date().toISOString());return}let s=this.hasUniqueIndexOnColumns("pending_messages",["session_db_id","tool_use_id"]);if(!(e&&s)){this.db.run("BEGIN TRANSACTION");try{this.recreatePendingSessionToolUniqueIndex(e),this.db.run("COMMIT")}catch(r){this.db.run("ROLLBACK");let n=r instanceof Error?r:new Error(String(r));throw d.error("DB","Failed to recreate ux_pending_session_tool index, rolled back",{},n),r}}}recreatePendingSessionToolUniqueIndex(e){this.db.run("DROP INDEX IF EXISTS ux_pending_session_tool"),this.db.run(`
136
+ DELETE FROM pending_messages
137
+ WHERE id IN (
138
+ SELECT id
139
+ FROM (
140
+ SELECT id,
141
+ ROW_NUMBER() OVER (
142
+ PARTITION BY session_db_id, tool_use_id
143
+ ORDER BY CASE status
144
+ WHEN 'processing' THEN 0
145
+ WHEN 'pending' THEN 1
146
+ ELSE 2
147
+ END, id
148
+ ) AS duplicate_rank
149
+ FROM pending_messages
150
+ WHERE tool_use_id IS NOT NULL
151
+ )
152
+ WHERE duplicate_rank > 1
153
+ )
154
+ `),this.db.run(`
155
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_pending_session_tool
156
+ ON pending_messages(session_db_id, tool_use_id)
157
+ WHERE tool_use_id IS NOT NULL
158
+ `),e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(35,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(o=>o.name)),n=["retry_count","failed_at_epoch","completed_at_epoch"].filter(o=>s.has(o));if(!(e&&n.length===0)){if(n.length>0){this.db.run("BEGIN TRANSACTION");try{this.db.run("DELETE FROM pending_messages WHERE status NOT IN ('pending', 'processing')");for(let o of n)this.db.run(`ALTER TABLE pending_messages DROP COLUMN ${o}`),d.debug("DB",`Dropped dead column ${o} 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(o){this.db.run("ROLLBACK"),d.warn("DB","Failed to drop dead columns from pending_messages",{},o instanceof Error?o:new Error(String(o)));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(`
159
+ CREATE TABLE IF NOT EXISTS schema_versions (
160
+ id INTEGER PRIMARY KEY,
161
+ version INTEGER UNIQUE NOT NULL,
162
+ applied_at TEXT NOT NULL
163
+ )
164
+ `),this.db.run(`
165
+ CREATE TABLE IF NOT EXISTS sdk_sessions (
166
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
167
+ content_session_id TEXT NOT NULL,
168
+ memory_session_id TEXT UNIQUE,
169
+ project TEXT NOT NULL,
170
+ platform_source TEXT NOT NULL DEFAULT 'claude',
171
+ user_prompt TEXT,
172
+ started_at TEXT NOT NULL,
173
+ started_at_epoch INTEGER NOT NULL,
174
+ completed_at TEXT,
175
+ completed_at_epoch INTEGER,
176
+ status TEXT CHECK(status IN ('active', 'completed', 'failed')) NOT NULL DEFAULT 'active'
177
+ );
178
+
179
+ CREATE INDEX IF NOT EXISTS idx_sdk_sessions_claude_id ON sdk_sessions(content_session_id);
180
+ CREATE INDEX IF NOT EXISTS idx_sdk_sessions_sdk_id ON sdk_sessions(memory_session_id);
181
+ CREATE INDEX IF NOT EXISTS idx_sdk_sessions_project ON sdk_sessions(project);
182
+ CREATE INDEX IF NOT EXISTS idx_sdk_sessions_status ON sdk_sessions(status);
183
+ CREATE INDEX IF NOT EXISTS idx_sdk_sessions_started ON sdk_sessions(started_at_epoch DESC);
184
+
185
+ CREATE TABLE IF NOT EXISTS observations (
186
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
187
+ memory_session_id TEXT NOT NULL,
188
+ project TEXT NOT NULL,
189
+ text TEXT NOT NULL,
190
+ type TEXT NOT NULL,
191
+ created_at TEXT NOT NULL,
192
+ created_at_epoch INTEGER NOT NULL,
193
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE ON UPDATE CASCADE
194
+ );
195
+
196
+ CREATE INDEX IF NOT EXISTS idx_observations_sdk_session ON observations(memory_session_id);
197
+ CREATE INDEX IF NOT EXISTS idx_observations_project ON observations(project);
198
+ CREATE INDEX IF NOT EXISTS idx_observations_type ON observations(type);
199
+ CREATE INDEX IF NOT EXISTS idx_observations_created ON observations(created_at_epoch DESC);
200
+
201
+ CREATE TABLE IF NOT EXISTS session_summaries (
202
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
203
+ memory_session_id TEXT UNIQUE NOT NULL,
204
+ project TEXT NOT NULL,
205
+ request TEXT,
206
+ investigated TEXT,
207
+ learned TEXT,
208
+ completed TEXT,
209
+ next_steps TEXT,
210
+ files_read TEXT,
211
+ files_edited TEXT,
212
+ notes TEXT,
213
+ created_at TEXT NOT NULL,
214
+ created_at_epoch INTEGER NOT NULL,
215
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE ON UPDATE CASCADE
216
+ );
217
+
218
+ CREATE INDEX IF NOT EXISTS idx_session_summaries_sdk_session ON session_summaries(memory_session_id);
219
+ CREATE INDEX IF NOT EXISTS idx_session_summaries_project ON session_summaries(project);
220
+ CREATE INDEX IF NOT EXISTS idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
221
+ `),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"),d.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(i=>i.name==="prompt_counter")||(this.db.run("ALTER TABLE sdk_sessions ADD COLUMN prompt_counter INTEGER DEFAULT 0"),d.debug("DB","Added prompt_counter column to sdk_sessions table")),this.db.query("PRAGMA table_info(observations)").all().some(i=>i.name==="prompt_number")||(this.db.run("ALTER TABLE observations ADD COLUMN prompt_number INTEGER"),d.debug("DB","Added prompt_number column to observations table")),this.db.query("PRAGMA table_info(session_summaries)").all().some(i=>i.name==="prompt_number")||(this.db.run("ALTER TABLE session_summaries ADD COLUMN prompt_number INTEGER"),d.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}d.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(`
222
+ CREATE TABLE session_summaries_new (
223
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
224
+ memory_session_id TEXT NOT NULL,
225
+ project TEXT NOT NULL,
226
+ request TEXT,
227
+ investigated TEXT,
228
+ learned TEXT,
229
+ completed TEXT,
230
+ next_steps TEXT,
231
+ files_read TEXT,
232
+ files_edited TEXT,
233
+ notes TEXT,
234
+ prompt_number INTEGER,
235
+ created_at TEXT NOT NULL,
236
+ created_at_epoch INTEGER NOT NULL,
237
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE
238
+ )
239
+ `),this.db.run(`
240
+ INSERT INTO session_summaries_new
241
+ SELECT id, memory_session_id, project, request, investigated, learned,
242
+ completed, next_steps, files_read, files_edited, notes,
243
+ prompt_number, created_at, created_at_epoch
244
+ FROM session_summaries
245
+ `),this.db.run("DROP TABLE session_summaries"),this.db.run("ALTER TABLE session_summaries_new RENAME TO session_summaries"),this.db.run(`
246
+ CREATE INDEX idx_session_summaries_sdk_session ON session_summaries(memory_session_id);
247
+ CREATE INDEX idx_session_summaries_project ON session_summaries(project);
248
+ CREATE INDEX idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
249
+ `),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString()),d.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(r=>r.name==="title")){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString());return}d.debug("DB","Adding hierarchical fields to observations table"),this.db.run(`
250
+ ALTER TABLE observations ADD COLUMN title TEXT;
251
+ ALTER TABLE observations ADD COLUMN subtitle TEXT;
252
+ ALTER TABLE observations ADD COLUMN facts TEXT;
253
+ ALTER TABLE observations ADD COLUMN narrative TEXT;
254
+ ALTER TABLE observations ADD COLUMN concepts TEXT;
255
+ ALTER TABLE observations ADD COLUMN files_read TEXT;
256
+ ALTER TABLE observations ADD COLUMN files_modified TEXT;
257
+ `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString()),d.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(r=>r.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}d.debug("DB","Making observations.text nullable"),this.db.run("BEGIN TRANSACTION"),this.db.run("DROP TABLE IF EXISTS observations_new"),this.db.run(`
258
+ CREATE TABLE observations_new (
259
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
260
+ memory_session_id TEXT NOT NULL,
261
+ project TEXT NOT NULL,
262
+ text TEXT,
263
+ type TEXT NOT NULL,
264
+ title TEXT,
265
+ subtitle TEXT,
266
+ facts TEXT,
267
+ narrative TEXT,
268
+ concepts TEXT,
269
+ files_read TEXT,
270
+ files_modified TEXT,
271
+ prompt_number INTEGER,
272
+ created_at TEXT NOT NULL,
273
+ created_at_epoch INTEGER NOT NULL,
274
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE
275
+ )
276
+ `),this.db.run(`
277
+ INSERT INTO observations_new
278
+ SELECT id, memory_session_id, project, text, type, title, subtitle, facts,
279
+ narrative, concepts, files_read, files_modified, prompt_number,
280
+ created_at, created_at_epoch
281
+ FROM observations
282
+ `),this.db.run("DROP TABLE observations"),this.db.run("ALTER TABLE observations_new RENAME TO observations"),this.db.run(`
283
+ CREATE INDEX idx_observations_sdk_session ON observations(memory_session_id);
284
+ CREATE INDEX idx_observations_project ON observations(project);
285
+ CREATE INDEX idx_observations_type ON observations(type);
286
+ CREATE INDEX idx_observations_created ON observations(created_at_epoch DESC);
287
+ `),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString()),d.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}d.debug("DB","Creating user_prompts table with FTS5 support"),this.db.run("BEGIN TRANSACTION"),this.db.run(`
288
+ CREATE TABLE user_prompts (
289
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
290
+ session_db_id INTEGER,
291
+ content_session_id TEXT NOT NULL,
292
+ prompt_number INTEGER NOT NULL,
293
+ prompt_text TEXT NOT NULL,
294
+ created_at TEXT NOT NULL,
295
+ created_at_epoch INTEGER NOT NULL,
296
+ FOREIGN KEY(session_db_id) REFERENCES sdk_sessions(id) ON DELETE CASCADE
297
+ );
298
+
299
+ CREATE INDEX idx_user_prompts_session ON user_prompts(session_db_id);
300
+ CREATE INDEX idx_user_prompts_claude_session ON user_prompts(content_session_id);
301
+ CREATE INDEX idx_user_prompts_created ON user_prompts(created_at_epoch DESC);
302
+ CREATE INDEX idx_user_prompts_prompt_number ON user_prompts(prompt_number);
303
+ CREATE INDEX idx_user_prompts_lookup ON user_prompts(session_db_id, prompt_number);
304
+ CREATE INDEX idx_user_prompts_content_lookup ON user_prompts(content_session_id, prompt_number);
305
+ `);let s=`
306
+ CREATE VIRTUAL TABLE user_prompts_fts USING fts5(
307
+ prompt_text,
308
+ content='user_prompts',
309
+ content_rowid='id'
310
+ );
311
+ `,r=`
312
+ CREATE TRIGGER user_prompts_ai AFTER INSERT ON user_prompts BEGIN
313
+ INSERT INTO user_prompts_fts(rowid, prompt_text)
314
+ VALUES (new.id, new.prompt_text);
315
+ END;
316
+
317
+ CREATE TRIGGER user_prompts_ad AFTER DELETE ON user_prompts BEGIN
318
+ INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text)
319
+ VALUES('delete', old.id, old.prompt_text);
320
+ END;
321
+
322
+ CREATE TRIGGER user_prompts_au AFTER UPDATE ON user_prompts BEGIN
323
+ INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text)
324
+ VALUES('delete', old.id, old.prompt_text);
325
+ INSERT INTO user_prompts_fts(rowid, prompt_text)
326
+ VALUES (new.id, new.prompt_text);
327
+ END;
328
+ `;try{this.db.run(s),this.db.run(r)}catch(n){n instanceof Error?d.warn("DB","FTS5 not available \u2014 user_prompts_fts skipped (search uses ChromaDB)",{},n):d.warn("DB","FTS5 not available \u2014 user_prompts_fts skipped (search uses ChromaDB)",{},new Error(String(n))),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString()),d.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()),d.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(o=>o.name==="discovery_tokens")||(this.db.run("ALTER TABLE observations ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),d.debug("DB","Added discovery_tokens column to observations table")),this.db.query("PRAGMA table_info(session_summaries)").all().some(o=>o.name==="discovery_tokens")||(this.db.run("ALTER TABLE session_summaries ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),d.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}d.debug("DB","Creating pending_messages table"),this.db.run(`
329
+ CREATE TABLE pending_messages (
330
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
331
+ session_db_id INTEGER NOT NULL,
332
+ content_session_id TEXT NOT NULL,
333
+ message_type TEXT NOT NULL CHECK(message_type IN ('observation', 'summarize')),
334
+ tool_name TEXT,
335
+ tool_input TEXT,
336
+ tool_response TEXT,
337
+ cwd TEXT,
338
+ last_user_message TEXT,
339
+ last_assistant_message TEXT,
340
+ prompt_number INTEGER,
341
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'processing')),
342
+ created_at_epoch INTEGER NOT NULL,
343
+ FOREIGN KEY (session_db_id) REFERENCES sdk_sessions(id) ON DELETE CASCADE
344
+ )
345
+ `),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_session ON pending_messages(session_db_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_status ON pending_messages(status)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_claude_session ON pending_messages(content_session_id)"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(16,new Date().toISOString()),d.debug("DB","pending_messages table created successfully")}renameSessionIdColumns(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(17))return;d.debug("DB","Checking session ID columns for semantic clarity rename");let t=0,s=(r,n,o)=>{let i=this.db.query(`PRAGMA table_info(${r})`).all(),p=i.some(u=>u.name===n);return i.some(u=>u.name===o)?!1:p?(this.db.run(`ALTER TABLE ${r} RENAME COLUMN ${n} TO ${o}`),d.debug("DB",`Renamed ${r}.${n} to ${o}`),!0):(d.warn("DB",`Column ${n} not found in ${r}, skipping rename`),!1)};s("sdk_sessions","claude_session_id","content_session_id")&&t++,s("sdk_sessions","sdk_session_id","memory_session_id")&&t++,s("pending_messages","claude_session_id","content_session_id")&&t++,s("observations","sdk_session_id","memory_session_id")&&t++,s("session_summaries","sdk_session_id","memory_session_id")&&t++,s("user_prompts","claude_session_id","content_session_id")&&t++,this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(17,new Date().toISOString()),t>0?d.debug("DB",`Successfully renamed ${t} session ID columns`):d.debug("DB","No session ID column renames needed (already up to date)")}addFailedAtEpochColumn(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(20))return;this.db.query("PRAGMA table_info(pending_messages)").all().some(r=>r.name==="failed_at_epoch")||(this.db.run("ALTER TABLE pending_messages ADD COLUMN failed_at_epoch INTEGER"),d.debug("DB","Added failed_at_epoch column to pending_messages table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(20,new Date().toISOString())}addOnUpdateCascadeToForeignKeys(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(21))return;d.debug("DB","Adding ON UPDATE CASCADE to FK constraints on observations and session_summaries"),this.db.run("PRAGMA foreign_keys = OFF"),this.db.run("BEGIN TRANSACTION"),this.db.run("DROP TRIGGER IF EXISTS observations_ai"),this.db.run("DROP TRIGGER IF EXISTS observations_ad"),this.db.run("DROP TRIGGER IF EXISTS observations_au"),this.db.run("DROP TABLE IF EXISTS observations_new");let t=this.db.query("PRAGMA table_info(observations)").all(),s=t.some(l=>l.name==="metadata"),r=t.some(l=>l.name==="content_hash"),n=s?`,
346
+ metadata TEXT`:"",o=s?", metadata":"",i=r?`,
347
+ content_hash TEXT`:"",p=r?", content_hash":"",_=`
348
+ CREATE TABLE observations_new (
349
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
350
+ memory_session_id TEXT NOT NULL,
351
+ project TEXT NOT NULL,
352
+ text TEXT,
353
+ type TEXT NOT NULL,
354
+ title TEXT,
355
+ subtitle TEXT,
356
+ facts TEXT,
357
+ narrative TEXT,
358
+ concepts TEXT,
359
+ files_read TEXT,
360
+ files_modified TEXT,
361
+ prompt_number INTEGER,
362
+ discovery_tokens INTEGER DEFAULT 0,
363
+ created_at TEXT NOT NULL,
364
+ created_at_epoch INTEGER NOT NULL${n}${i},
365
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE ON UPDATE CASCADE
366
+ )
367
+ `,u=`
368
+ INSERT INTO observations_new
369
+ SELECT id, memory_session_id, project, text, type, title, subtitle, facts,
370
+ narrative, concepts, files_read, files_modified, prompt_number,
371
+ discovery_tokens, created_at, created_at_epoch${o}${p}
372
+ FROM observations
373
+ `,I=`
374
+ CREATE INDEX idx_observations_sdk_session ON observations(memory_session_id);
375
+ CREATE INDEX idx_observations_project ON observations(project);
376
+ CREATE INDEX idx_observations_type ON observations(type);
377
+ CREATE INDEX idx_observations_created ON observations(created_at_epoch DESC);
378
+ `,c=`
379
+ CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN
380
+ INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts)
381
+ VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts);
382
+ END;
383
+
384
+ CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN
385
+ INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts)
386
+ VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts);
387
+ END;
388
+
389
+ CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN
390
+ INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts)
391
+ VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts);
392
+ INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts)
393
+ VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts);
394
+ END;
395
+ `;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 N=`
396
+ CREATE TABLE session_summaries_new (
397
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
398
+ memory_session_id TEXT NOT NULL,
399
+ project TEXT NOT NULL,
400
+ request TEXT,
401
+ investigated TEXT,
402
+ learned TEXT,
403
+ completed TEXT,
404
+ next_steps TEXT,
405
+ files_read TEXT,
406
+ files_edited TEXT,
407
+ notes TEXT,
408
+ prompt_number INTEGER,
409
+ discovery_tokens INTEGER DEFAULT 0,
410
+ created_at TEXT NOT NULL,
411
+ created_at_epoch INTEGER NOT NULL,
412
+ FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id) ON DELETE CASCADE ON UPDATE CASCADE
413
+ )
414
+ `,O=`
415
+ INSERT INTO session_summaries_new
416
+ SELECT id, memory_session_id, project, request, investigated, learned,
417
+ completed, next_steps, files_read, files_edited, notes,
418
+ prompt_number, discovery_tokens, created_at, created_at_epoch
419
+ FROM session_summaries
420
+ `,R=`
421
+ CREATE INDEX idx_session_summaries_sdk_session ON session_summaries(memory_session_id);
422
+ CREATE INDEX idx_session_summaries_project ON session_summaries(project);
423
+ CREATE INDEX idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
424
+ `,m=`
425
+ CREATE TRIGGER IF NOT EXISTS session_summaries_ai AFTER INSERT ON session_summaries BEGIN
426
+ INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
427
+ VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes);
428
+ END;
429
+
430
+ CREATE TRIGGER IF NOT EXISTS session_summaries_ad AFTER DELETE ON session_summaries BEGIN
431
+ INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes)
432
+ VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes);
433
+ END;
434
+
435
+ CREATE TRIGGER IF NOT EXISTS session_summaries_au AFTER UPDATE ON session_summaries BEGIN
436
+ INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes)
437
+ VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes);
438
+ INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
439
+ VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes);
440
+ END;
441
+ `;try{this.recreateObservationsWithCascade(_,u,I,c),this.recreateSessionSummariesWithCascade(N,O,R,m),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(21,new Date().toISOString()),this.db.run("COMMIT"),this.db.run("PRAGMA foreign_keys = ON"),d.debug("DB","Successfully added ON UPDATE CASCADE to FK constraints")}catch(l){throw this.db.run("ROLLBACK"),this.db.run("PRAGMA foreign_keys = ON"),l instanceof Error?l:new Error(String(l))}}recreateObservationsWithCascade(e,t,s,r){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(r)}recreateSessionSummariesWithCascade(e,t,s,r){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(r)}addObservationContentHashColumn(){if(this.db.query("PRAGMA table_info(observations)").all().some(s=>s.name==="content_hash")){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(22,new Date().toISOString());return}this.db.run("ALTER TABLE observations ADD COLUMN content_hash TEXT"),this.db.run("UPDATE observations SET content_hash = substr(hex(randomblob(8)), 1, 16) WHERE content_hash IS NULL"),this.db.run("CREATE INDEX IF NOT EXISTS idx_observations_content_hash ON observations(content_hash, created_at_epoch)"),d.debug("DB","Added content_hash column to observations table with backfill and index"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(22,new Date().toISOString())}addSessionCustomTitleColumn(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(23),s=this.db.query("PRAGMA table_info(sdk_sessions)").all().some(r=>r.name==="custom_title");e&&s||(s||(this.db.run("ALTER TABLE sdk_sessions ADD COLUMN custom_title TEXT"),d.debug("DB","Added custom_title column to sdk_sessions table")),e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(23,new Date().toISOString()))}addSessionPlatformSourceColumn(){let t=this.db.query("PRAGMA table_info(sdk_sessions)").all().some(o=>o.name==="platform_source"),r=this.db.query("PRAGMA index_list(sdk_sessions)").all().some(o=>o.name==="idx_sdk_sessions_platform_source");this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(24)&&t&&r||(t||(this.db.run(`ALTER TABLE sdk_sessions ADD COLUMN platform_source TEXT NOT NULL DEFAULT '${E}'`),d.debug("DB","Added platform_source column to sdk_sessions table")),this.db.run(`
442
+ UPDATE sdk_sessions
443
+ SET platform_source = '${E}'
444
+ WHERE platform_source IS NULL OR platform_source = ''
445
+ `),r||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(r=>r.name==="generated_by_model"),s=e.some(r=>r.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(o=>o.name==="agent_type"),r=t.some(o=>o.name==="agent_id");s||this.db.run("ALTER TABLE observations ADD COLUMN agent_type TEXT"),r||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 n=this.db.query("PRAGMA table_info(pending_messages)").all();if(n.length>0){let o=n.some(p=>p.name==="agent_type"),i=n.some(p=>p.name==="agent_id");o||this.db.run("ALTER TABLE pending_messages ADD COLUMN agent_type TEXT"),i||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(r=>r.name==="tool_use_id")||this.db.run("ALTER TABLE pending_messages ADD COLUMN tool_use_id TEXT"),this.db.run("BEGIN TRANSACTION");try{this.dedupePendingMessagesByToolUseId(),this.db.run("COMMIT")}catch(r){this.db.run("ROLLBACK");let n=r instanceof Error?r:new Error(String(r));throw d.error("DB","Failed to de-dupe pending_messages by tool_use_id, rolled back",{},n),r}}dedupePendingMessagesByToolUseId(){this.db.run(`
446
+ DELETE FROM pending_messages
447
+ WHERE id IN (
448
+ SELECT id
449
+ FROM (
450
+ SELECT id,
451
+ ROW_NUMBER() OVER (
452
+ PARTITION BY session_db_id, tool_use_id
453
+ ORDER BY CASE status
454
+ WHEN 'processing' THEN 0
455
+ WHEN 'pending' THEN 1
456
+ ELSE 2
457
+ END, id
458
+ ) AS duplicate_rank
459
+ FROM pending_messages
460
+ WHERE tool_use_id IS NOT NULL
461
+ )
462
+ WHERE duplicate_rank > 1
463
+ )
464
+ `),this.db.run(`
465
+ -- tool_use_id is optional for summaries and legacy rows; enforce de-dupe
466
+ -- only for rows that came from a concrete tool-use event.
467
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_pending_session_tool
468
+ ON pending_messages(session_db_id, tool_use_id)
469
+ WHERE tool_use_id IS NOT NULL
470
+ `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(28,new Date().toISOString())}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(n=>n.name==="memory_session_id"),r=t.some(n=>n.name==="content_hash");if(!s||!r){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.dedupeObservationsByContentHash(),this.db.run("COMMIT")}catch(n){this.db.run("ROLLBACK");let o=n instanceof Error?n:new Error(String(n));throw d.error("DB","Failed to de-dupe observations by content_hash, rolled back",{},o),n}}dedupeObservationsByContentHash(){this.db.run(`
471
+ UPDATE observations
472
+ SET content_hash = '__null_migration_' || id || '__'
473
+ WHERE content_hash IS NULL
474
+ `),this.db.run(`
475
+ DELETE FROM observations
476
+ WHERE id IN (
477
+ SELECT id
478
+ FROM (
479
+ SELECT id,
480
+ ROW_NUMBER() OVER (
481
+ PARTITION BY memory_session_id, content_hash
482
+ ORDER BY id
483
+ ) AS duplicate_rank
484
+ FROM observations
485
+ )
486
+ WHERE duplicate_rank > 1
487
+ )
488
+ `),this.db.run(`
489
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_observations_session_hash
490
+ ON observations(memory_session_id, content_hash)
491
+ `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(29,new Date().toISOString())}addObservationsMetadataColumn(){this.db.query("PRAGMA table_info(observations)").all().some(s=>s.name==="metadata")||(this.db.run("ALTER TABLE observations ADD COLUMN metadata TEXT"),d.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(`
492
+ UPDATE sdk_sessions
493
+ SET memory_session_id = ?
494
+ WHERE id = ?
495
+ `).run(t,e)}markSessionCompleted(e){let t=Date.now(),s=new Date(t).toISOString();this.db.prepare(`
496
+ UPDATE sdk_sessions
497
+ SET status = 'completed', completed_at = ?, completed_at_epoch = ?
498
+ WHERE id = ?
499
+ `).run(s,t,e)}ensureMemorySessionIdRegistered(e,t,s){let r=this.db.prepare(`
500
+ SELECT id, memory_session_id, worker_port FROM sdk_sessions WHERE id = ?
501
+ `).get(e);if(!r)throw new Error(`Session ${e} not found in sdk_sessions`);r.memory_session_id!==t&&(this.db.prepare(`
502
+ UPDATE sdk_sessions SET memory_session_id = ? WHERE id = ?
503
+ `).run(t,e),d.info("DB","Registered memory_session_id before storage (FK fix)",{sessionDbId:e,oldId:r.memory_session_id,newId:t})),typeof s=="number"&&r.worker_port!==s&&this.db.prepare(`
504
+ UPDATE sdk_sessions SET worker_port = ? WHERE id = ?
505
+ `).run(s,e)}getAllProjects(e){let t=e?L(e):void 0,s=`
506
+ SELECT DISTINCT project
507
+ FROM sdk_sessions
508
+ WHERE project IS NOT NULL AND project != ''
509
+ AND project != ?
510
+ `,r=[k];return t&&(s+=" AND COALESCE(platform_source, ?) = ?",r.push(E,t)),s+=" ORDER BY project ASC",this.db.prepare(s).all(...r).map(o=>o.project)}getProjectCatalog(){let e=this.db.prepare(`
511
+ SELECT
512
+ COALESCE(platform_source, '${E}') as platform_source,
513
+ project,
514
+ MAX(started_at_epoch) as latest_epoch
515
+ FROM sdk_sessions
516
+ WHERE project IS NOT NULL AND project != ''
517
+ AND project != ?
518
+ GROUP BY COALESCE(platform_source, '${E}'), project
519
+ ORDER BY latest_epoch DESC
520
+ `).all(k),t=[],s=new Set,r={};for(let o of e){let i=L(o.platform_source);r[i]||(r[i]=[]),r[i].includes(o.project)||r[i].push(o.project),s.has(o.project)||(s.add(o.project),t.push(o.project))}let n=J(Object.keys(r));return{projects:t,sources:n,projectsBySource:Object.fromEntries(n.map(o=>[o,r[o]||[]]))}}getLatestUserPrompt(e,t){let s=this.resolvePromptSessionDbId(e,t),r=s!==null?"up.session_db_id = ?":"up.content_session_id = ?",n=s!==null?s:e;return this.db.prepare(`
521
+ SELECT
522
+ up.*,
523
+ s.memory_session_id,
524
+ s.project,
525
+ COALESCE(s.platform_source, '${E}') as platform_source
526
+ FROM user_prompts up
527
+ JOIN sdk_sessions s ON up.session_db_id = s.id
528
+ WHERE ${r}
529
+ ORDER BY up.created_at_epoch DESC
530
+ LIMIT 1
531
+ `).get(n)}findRecentDuplicateUserPrompt(e,t,s,r){return z(this.db,e,F(t),s,this.resolvePromptSessionDbId(e,r)??void 0)}getRecentSessionsWithStatus(e,t=3,s){let r=[e],n="";return s&&(n=`AND COALESCE(NULLIF(s.platform_source, ''), '${E}') = ?`,r.push(L(s))),r.push(t),this.db.prepare(`
532
+ SELECT * FROM (
533
+ SELECT
534
+ s.memory_session_id,
535
+ s.status,
536
+ s.started_at,
537
+ s.started_at_epoch,
538
+ s.user_prompt,
539
+ CASE WHEN sum.memory_session_id IS NOT NULL THEN 1 ELSE 0 END as has_summary
540
+ FROM sdk_sessions s
541
+ LEFT JOIN session_summaries sum ON s.memory_session_id = sum.memory_session_id
542
+ WHERE s.project = ? AND s.memory_session_id IS NOT NULL
543
+ ${n}
544
+ GROUP BY s.memory_session_id
545
+ ORDER BY s.started_at_epoch DESC
546
+ LIMIT ?
547
+ )
548
+ ORDER BY started_at_epoch ASC
549
+ `).all(...r)}getObservationsForSession(e,t){let s=[e],r="";return t&&(r=`
550
+ AND EXISTS (
551
+ SELECT 1
552
+ FROM sdk_sessions s
553
+ WHERE s.memory_session_id = observations.memory_session_id
554
+ AND COALESCE(NULLIF(s.platform_source, ''), '${E}') = ?
555
+ )
556
+ `,s.push(L(t))),this.db.prepare(`
557
+ SELECT title, subtitle, type, prompt_number
558
+ FROM observations
559
+ WHERE memory_session_id = ?
560
+ ${r}
561
+ ORDER BY created_at_epoch ASC
562
+ `).all(...s)}getObservationById(e,t){return t?this.db.prepare(`
563
+ SELECT o.*
564
+ FROM observations o
565
+ LEFT JOIN sdk_sessions s ON s.memory_session_id = o.memory_session_id
566
+ WHERE o.id = ?
567
+ AND COALESCE(NULLIF(s.platform_source, ''), '${E}') = ?
568
+ `).get(e,L(t))||null:this.db.prepare(`
569
+ SELECT *
570
+ FROM observations
571
+ WHERE id = ?
572
+ `).get(e)||null}getObservationsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:r,project:n,platformSource:o,type:i,concepts:p,files:_}=t,u=s==="relevance",I=u?"":`ORDER BY o.created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,c=r&&!u?`LIMIT ${r}`:"",N=e.map(()=>"?").join(","),O=[...e],R=[];if(n&&(R.push("o.project = ?"),O.push(n)),o&&(R.push(`COALESCE(NULLIF(s.platform_source, ''), '${E}') = ?`),O.push(L(o))),i)if(Array.isArray(i)){let h=i.map(()=>"?").join(",");R.push(`o.type IN (${h})`),O.push(...i)}else R.push("o.type = ?"),O.push(i);if(p){let h=Array.isArray(p)?p:[p],b=h.map(()=>"EXISTS (SELECT 1 FROM json_each(o.concepts) WHERE value = ?)");O.push(...h),R.push(`(${b.join(" OR ")})`)}if(_){let h=Array.isArray(_)?_:[_],b=h.map(()=>"(EXISTS (SELECT 1 FROM json_each(o.files_read) WHERE value LIKE ?) OR EXISTS (SELECT 1 FROM json_each(o.files_modified) WHERE value LIKE ?))");h.forEach(A=>{O.push(`%${A}%`,`%${A}%`)}),R.push(`(${b.join(" OR ")})`)}let m=R.length>0?`WHERE o.id IN (${N}) AND ${R.join(" AND ")}`:`WHERE o.id IN (${N})`,f=this.db.prepare(`
573
+ SELECT o.*
574
+ FROM observations o
575
+ LEFT JOIN sdk_sessions s ON s.memory_session_id = o.memory_session_id
576
+ ${m}
577
+ ${I}
578
+ ${c}
579
+ `).all(...O);if(!u)return f;let v=new Map(f.map(h=>[h.id,h])),T=e.map(h=>v.get(h)).filter(h=>!!h);return r?T.slice(0,r):T}getSummaryForSession(e,t){let s=[e],r="";return t&&(r=`
580
+ AND EXISTS (
581
+ SELECT 1
582
+ FROM sdk_sessions sdk
583
+ WHERE sdk.memory_session_id = session_summaries.memory_session_id
584
+ AND COALESCE(NULLIF(sdk.platform_source, ''), '${E}') = ?
585
+ )
586
+ `,s.push(L(t))),this.db.prepare(`
587
+ SELECT
588
+ request, investigated, learned, completed, next_steps,
589
+ files_read, files_edited, notes, prompt_number, created_at,
590
+ created_at_epoch
591
+ FROM session_summaries
592
+ WHERE memory_session_id = ?
593
+ ${r}
594
+ ORDER BY created_at_epoch DESC
595
+ LIMIT 1
596
+ `).get(...s)||null}getSessionById(e){return this.db.prepare(`
597
+ SELECT id, content_session_id, memory_session_id, project,
598
+ COALESCE(platform_source, '${E}') as platform_source,
599
+ user_prompt, custom_title, status
600
+ FROM sdk_sessions
601
+ WHERE id = ?
602
+ LIMIT 1
603
+ `).get(e)||null}getSdkSessionsBySessionIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.db.prepare(`
604
+ SELECT id, content_session_id, memory_session_id, project,
605
+ COALESCE(platform_source, '${E}') as platform_source,
606
+ user_prompt, custom_title,
607
+ started_at, started_at_epoch, completed_at, completed_at_epoch, status
608
+ FROM sdk_sessions
609
+ WHERE memory_session_id IN (${t})
610
+ ORDER BY started_at_epoch DESC
611
+ `).all(...e)}getPromptNumberFromUserPrompts(e,t){let s=this.resolvePromptSessionDbId(e,t);return s!==null?this.db.prepare(`
612
+ SELECT COUNT(*) as count FROM user_prompts WHERE session_db_id = ?
613
+ `).get(s).count:this.db.prepare(`
614
+ SELECT COUNT(*) as count FROM user_prompts WHERE content_session_id = ?
615
+ `).get(e).count}createSDKSession(e,t,s,r,n){let o=new Date,i=o.getTime(),p=n?L(n):E,_=F(s),u=this.db.prepare(`
616
+ SELECT id, platform_source
617
+ FROM sdk_sessions
618
+ WHERE COALESCE(NULLIF(platform_source, ''), ?) = ?
619
+ AND content_session_id = ?
620
+ `).get(E,p,e);if(u)return t&&this.db.prepare(`
621
+ UPDATE sdk_sessions SET project = ?
622
+ WHERE id = ? AND (project IS NULL OR project = '')
623
+ `).run(t,u.id),r&&this.db.prepare(`
624
+ UPDATE sdk_sessions SET custom_title = ?
625
+ WHERE id = ? AND custom_title IS NULL
626
+ `).run(r,u.id),u.id;let I=this.db.prepare(`
627
+ INSERT INTO sdk_sessions
628
+ (content_session_id, memory_session_id, project, platform_source, user_prompt, custom_title, started_at, started_at_epoch, status)
629
+ VALUES (?, NULL, ?, ?, ?, ?, ?, ?, 'active')
630
+ `).run(e,t,p,_,r||null,o.toISOString(),i);return Number(I.lastInsertRowid)}saveUserPrompt(e,t,s,r){let n=new Date,o=n.getTime(),i=F(s),p=this.resolvePromptSessionDbId(e,r);return this.db.prepare(`
631
+ INSERT INTO user_prompts
632
+ (session_db_id, content_session_id, prompt_number, prompt_text, created_at, created_at_epoch)
633
+ VALUES (?, ?, ?, ?, ?, ?)
634
+ `).run(p,e,t,i,n.toISOString(),o).lastInsertRowid}getUserPrompt(e,t,s){let r=this.resolvePromptSessionDbId(e,s);return r!==null?this.db.prepare(`
635
+ SELECT prompt_text
636
+ FROM user_prompts
637
+ WHERE session_db_id = ? AND prompt_number = ?
638
+ LIMIT 1
639
+ `).get(r,t)?.prompt_text??null:this.db.prepare(`
640
+ SELECT prompt_text
641
+ FROM user_prompts
642
+ WHERE content_session_id = ? AND prompt_number = ?
643
+ LIMIT 1
644
+ `).get(e,t)?.prompt_text??null}storeObservation(e,t,s,r,n=0,o,i){let p=this.storeObservations(e,t,[s],null,r,n,o,i);return{id:p.observationIds[0],createdAtEpoch:p.createdAtEpoch}}storeSummary(e,t,s,r,n=0,o){let i=o??Date.now(),p=new Date(i).toISOString(),u=this.db.prepare(`
645
+ INSERT INTO session_summaries
646
+ (memory_session_id, project, request, investigated, learned, completed,
647
+ next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
648
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
649
+ `).run(e,t,s.request,s.investigated,s.learned,s.completed,s.next_steps,s.notes,r||null,n,p,i);return{id:Number(u.lastInsertRowid),createdAtEpoch:i}}storeObservations(e,t,s,r,n,o=0,i,p){let _=i??Date.now(),u=new Date(_).toISOString();return this.db.transaction(()=>{let c=[],N=this.db.prepare(`
650
+ INSERT INTO observations
651
+ (memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
652
+ files_read, files_modified, prompt_number, discovery_tokens, agent_type, agent_id, content_hash, created_at, created_at_epoch,
653
+ generated_by_model, metadata)
654
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
655
+ ON CONFLICT(memory_session_id, content_hash) DO NOTHING
656
+ RETURNING id
657
+ `),O=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let m of s){let l=Q(e,m.title,m.narrative),f=N.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),n||null,o,m.agent_type??null,m.agent_id??null,l,u,_,p||null,m.metadata??null);if(f){c.push(f.id);continue}let v=O.get(e,l);if(!v)throw new Error(`storeObservations: ON CONFLICT without existing row for content_hash=${l}`);c.push(v.id)}let R=null;if(r){let l=this.db.prepare(`
658
+ INSERT INTO session_summaries
659
+ (memory_session_id, project, request, investigated, learned, completed,
660
+ next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
661
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
662
+ `).run(e,t,r.request,r.investigated,r.learned,r.completed,r.next_steps,r.notes,n||null,o,u,_);R=Number(l.lastInsertRowid)}return{observationIds:c,summaryId:R,createdAtEpoch:_}})()}getSessionSummariesByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:r,project:n,platformSource:o}=t,i=s==="relevance",p=i?"":`ORDER BY ss.created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,_=r&&!i?`LIMIT ${r}`:"",u=e.map(()=>"?").join(","),I=[...e],c=[];n&&(c.push("ss.project = ?"),I.push(n)),o&&(c.push(`COALESCE(NULLIF(s.platform_source, ''), '${E}') = ?`),I.push(L(o)));let N=c.length>0?`AND ${c.join(" AND ")}`:"",R=this.db.prepare(`
663
+ SELECT ss.*
664
+ FROM session_summaries ss
665
+ LEFT JOIN sdk_sessions s ON s.memory_session_id = ss.memory_session_id
666
+ WHERE ss.id IN (${u}) ${N}
667
+ ${p}
668
+ ${_}
669
+ `).all(...I);if(!i)return R;let m=new Map(R.map(f=>[f.id,f])),l=e.map(f=>m.get(f)).filter(f=>!!f);return r?l.slice(0,r):l}getUserPromptsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:r,project:n,platformSource:o}=t,i=s==="relevance",p=i?"":`ORDER BY up.created_at_epoch ${s==="date_asc"?"ASC":"DESC"}`,_=r?`LIMIT ${r}`:"",u=e.map(()=>"?").join(","),I=[...e],c=[];n&&(c.push("s.project = ?"),I.push(n)),o&&(c.push(`COALESCE(NULLIF(s.platform_source, ''), '${E}') = ?`),I.push(L(o)));let N=c.length>0?`AND ${c.join(" AND ")}`:"",R=this.db.prepare(`
670
+ SELECT
671
+ up.*,
672
+ s.project,
673
+ s.memory_session_id,
674
+ COALESCE(NULLIF(s.platform_source, ''), '${E}') as platform_source
675
+ FROM user_prompts up
676
+ JOIN sdk_sessions s ON up.session_db_id = s.id
677
+ WHERE up.id IN (${u}) ${N}
678
+ ${p}
679
+ ${_}
680
+ `).all(...I);if(!i)return R;let m=new Map(R.map(l=>[l.id,l]));return e.map(l=>m.get(l)).filter(l=>!!l)}getTimelineAroundTimestamp(e,t=10,s=10,r,n){return this.getTimelineAroundObservation(null,e,t,s,r,n)}getTimelineAroundObservation(e,t,s=10,r=10,n,o){let i=o?L(o):void 0,p=(T,h)=>{let b=[],A=[];return n&&(b.push(`${T}.project = ?`),A.push(n)),i&&(b.push(`COALESCE(NULLIF(${h}.platform_source, ''), '${E}') = ?`),A.push(i)),{clause:b.length>0?`AND ${b.join(" AND ")}`:"",params:A}},_=p("o","src"),u=p("ss","src"),I=p("s","s"),c,N;if(e!==null){let T=`
681
+ SELECT o.id, o.created_at_epoch
682
+ FROM observations o
683
+ LEFT JOIN sdk_sessions src ON src.memory_session_id = o.memory_session_id
684
+ WHERE o.id <= ? ${_.clause}
685
+ ORDER BY o.id DESC
686
+ LIMIT ?
687
+ `,h=`
688
+ SELECT o.id, o.created_at_epoch
689
+ FROM observations o
690
+ LEFT JOIN sdk_sessions src ON src.memory_session_id = o.memory_session_id
691
+ WHERE o.id >= ? ${_.clause}
692
+ ORDER BY o.id ASC
693
+ LIMIT ?
694
+ `;try{let b=this.db.prepare(T).all(e,..._.params,s+1),A=this.db.prepare(h).all(e,..._.params,r+1);if(b.length===0&&A.length===0)return{observations:[],sessions:[],prompts:[]};c=b.length>0?b[b.length-1].created_at_epoch:t,N=A.length>0?A[A.length-1].created_at_epoch:t}catch(b){return b instanceof Error?d.error("DB","Error getting boundary observations",{project:n},b):d.error("DB","Error getting boundary observations with non-Error",{},new Error(String(b))),{observations:[],sessions:[],prompts:[]}}}else{let T=`
695
+ SELECT o.created_at_epoch
696
+ FROM observations o
697
+ LEFT JOIN sdk_sessions src ON src.memory_session_id = o.memory_session_id
698
+ WHERE o.created_at_epoch <= ? ${_.clause}
699
+ ORDER BY o.created_at_epoch DESC
700
+ LIMIT ?
701
+ `,h=`
702
+ SELECT o.created_at_epoch
703
+ FROM observations o
704
+ LEFT JOIN sdk_sessions src ON src.memory_session_id = o.memory_session_id
705
+ WHERE o.created_at_epoch >= ? ${_.clause}
706
+ ORDER BY o.created_at_epoch ASC
707
+ LIMIT ?
708
+ `;try{let b=this.db.prepare(T).all(t,..._.params,s),A=this.db.prepare(h).all(t,..._.params,r+1);if(b.length===0&&A.length===0)return{observations:[],sessions:[],prompts:[]};c=b.length>0?b[b.length-1].created_at_epoch:t,N=A.length>0?A[A.length-1].created_at_epoch:t}catch(b){return b instanceof Error?d.error("DB","Error getting boundary timestamps",{project:n},b):d.error("DB","Error getting boundary timestamps with non-Error",{},new Error(String(b))),{observations:[],sessions:[],prompts:[]}}}let O=`
709
+ SELECT o.*
710
+ FROM observations o
711
+ LEFT JOIN sdk_sessions src ON src.memory_session_id = o.memory_session_id
712
+ WHERE o.created_at_epoch >= ? AND o.created_at_epoch <= ? ${_.clause}
713
+ ORDER BY o.created_at_epoch ASC
714
+ `,R=`
715
+ SELECT ss.*
716
+ FROM session_summaries ss
717
+ LEFT JOIN sdk_sessions src ON src.memory_session_id = ss.memory_session_id
718
+ WHERE ss.created_at_epoch >= ? AND ss.created_at_epoch <= ? ${u.clause}
719
+ ORDER BY ss.created_at_epoch ASC
720
+ `,m=`
721
+ SELECT up.*, s.project, s.memory_session_id, COALESCE(NULLIF(s.platform_source, ''), '${E}') as platform_source
722
+ FROM user_prompts up
723
+ JOIN sdk_sessions s ON up.session_db_id = s.id
724
+ WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${I.clause}
725
+ ORDER BY up.created_at_epoch ASC
726
+ `,l=this.db.prepare(O).all(c,N,..._.params),f=this.db.prepare(R).all(c,N,...u.params),v=this.db.prepare(m).all(c,N,...I.params);return{observations:l,sessions:f.map(T=>({id:T.id,memory_session_id:T.memory_session_id,project:T.project,request:T.request,completed:T.completed,next_steps:T.next_steps,created_at:T.created_at,created_at_epoch:T.created_at_epoch})),prompts:v.map(T=>({id:T.id,content_session_id:T.content_session_id,prompt_number:T.prompt_number,prompt_text:T.prompt_text,project:T.project,platform_source:T.platform_source,created_at:T.created_at,created_at_epoch:T.created_at_epoch}))}}getOrCreateManualSession(e){let t=`manual-${e}`,s=`manual-content-${e}`;if(this.db.prepare("SELECT memory_session_id FROM sdk_sessions WHERE memory_session_id = ?").get(t))return t;let n=new Date;return this.db.prepare(`
727
+ INSERT INTO sdk_sessions (memory_session_id, content_session_id, project, platform_source, started_at, started_at_epoch, status)
728
+ VALUES (?, ?, ?, ?, ?, ?, 'active')
729
+ `).run(t,s,e,E,n.toISOString(),n.getTime()),d.info("SESSION","Created manual session",{memorySessionId:t,project:e}),t}close(){this.db.close()}importSdkSession(e){let t=L(e.platform_source),s=this.db.prepare(`SELECT id FROM sdk_sessions
730
+ WHERE platform_source = ? AND content_session_id = ?`).get(t,e.content_session_id);return s?{imported:!1,id:s.id}:{imported:!0,id:this.db.prepare(`
731
+ INSERT INTO sdk_sessions (
732
+ content_session_id, memory_session_id, project, platform_source, user_prompt,
733
+ started_at, started_at_epoch, completed_at, completed_at_epoch, status
734
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
735
+ `).run(e.content_session_id,e.memory_session_id,e.project,t,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(`
736
+ INSERT INTO session_summaries (
737
+ memory_session_id, project, request, investigated, learned,
738
+ completed, next_steps, files_read, files_edited, notes,
739
+ prompt_number, discovery_tokens, created_at, created_at_epoch
740
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
741
+ `).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(`
742
+ SELECT id FROM observations
743
+ WHERE memory_session_id = ? AND title = ? AND created_at_epoch = ?
744
+ `).get(e.memory_session_id,e.title,e.created_at_epoch);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(`
745
+ INSERT INTO observations (
746
+ memory_session_id, project, text, type, title, subtitle,
747
+ facts, narrative, concepts, files_read, files_modified,
748
+ prompt_number, discovery_tokens, agent_type, agent_id,
749
+ created_at, created_at_epoch
750
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
751
+ `).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=null,s=e.platform_source?L(e.platform_source):void 0;if(typeof e.session_db_id=="number"){let i=this.db.prepare(`
752
+ SELECT id, content_session_id, COALESCE(NULLIF(platform_source, ''), '${E}') as platform_source
753
+ FROM sdk_sessions
754
+ WHERE id = ?
755
+ LIMIT 1
756
+ `).get(e.session_db_id);i&&i.content_session_id===e.content_session_id&&(!s||L(i.platform_source)===s)&&(t=i.id)}t===null&&(t=this.resolvePromptSessionDbId(e.content_session_id,void 0,s));let r=this.db.prepare(`
757
+ SELECT id FROM user_prompts
758
+ WHERE ${t!==null?"session_db_id = ?":"content_session_id = ?"} AND prompt_number = ?
759
+ `).get(t??e.content_session_id,e.prompt_number);return r?{imported:!1,id:r.id}:{imported:!0,id:this.db.prepare(`
760
+ INSERT INTO user_prompts (
761
+ session_db_id, content_session_id, prompt_number, prompt_text,
762
+ created_at, created_at_epoch
763
+ ) VALUES (?, ?, ?, ?, ?, ?)
764
+ `).run(t,e.content_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};0&&(module.exports={SessionStore});