MCPcopy
hub / github.com/mksglu/context-mode / insertEvent

Method insertEvent

cli.bundle.mjs:144–144  ·  view source on GitHub ↗
(e,n,r="PostToolUse",o,s)

Source from the content-addressed store, hash-verified

142 FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(F.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
143 COALESCE(SUM(bytes_returned), 0) AS bytes_returned
144 FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=Ri("sha256").update(n.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??n.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??n.attribution_source??"unknown"),u=Number(o?.confidence??n.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=Ec(s?.bytesAvoided),p=Ec(s?.bytesReturned),f=this.db.transaction(()=>{if(this.stmt(F.checkDuplicate).get(e,fx,n.type,i))return;this.stmt(F.getEventCount).get(e).cnt>=mx&&this.stmt(F.evictLowestPriority).run(e),this.stmt(F.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,p,r,i),this.stmt(F.updateMetaLastEvent).run(e)});this.withRetry(()=>f())}bulkInsertEvents(e,n,r="PostToolUse",o,s){if(!n||n.length===0)return;if(n.length===1){this.insertEvent(e,n[0],r,o?.[0],s?.[0]);return}let i=n.map((c,u)=>{let l=Ri("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],p=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),f=p===""?"":yr(p),m=String(d?.source??c.attribution_source??"unknown"),h=Number(d?.confidence??c.attribution_confidence??0),g=Number.isFinite(h)?Math.max(0,Math.min(1,h)):0,y=s?.[u],_=Ec(y?.bytesAvoided),b=Ec(y?.bytesReturned);return{event:c,dataHash:l,projectDir:f,attributionSource:m,attributionConfidence:g,bytesAvoided:_,bytesReturned:b}}),a=this.db.transaction(()=>{let c=this.stmt(F.getEventCount).get(e).cnt;for(let u of i)this.stmt(F.checkDuplicate).get(e,fx,u.event.type,u.dataHash)||(c>=mx?this.stmt(F.evictLowestPriority).run(e):c++,this.stmt(F.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,r,u.dataHash));this.stmt(F.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,n){let r=n?.limit??1e3,o=n?.type,s=n?.minPriority;return o&&s!==void 0?this.stmt(F.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(F.getEventsByType).all(e,o,r):s!==void 0?this.stmt(F.getEventsByPriority).all(e,s,r):this.stmt(F.getEvents).all(e,r)}getEventCount(e){return this.stmt(F.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(F.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(F.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,n,r,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(F.searchEvents).all(r,s,s,i,i,n)}catch{return[]}}getSessionIdsForProject(e){try{let n=yr(e);return this.db.prepare(`SELECT DISTINCT session_id
145 FROM session_events
146 WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch{return[]}}ensureSession(e,n){this.stmt(F.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(F.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(F.getSessionRollup).get(e),r=this.stmt(F.getMaxFileEdits).get(e),o=this.stmt(F.getLatestCommitMessage).get(e),s=this.getSessionStats(e),i=(n?.tool_calls??0)>0?n?.unique_files??0:0,a=n?.errors??0,c=Math.min(i,a);return{tool_calls:n?.tool_calls??0,errors:n?.errors??0,unique_tools:n?.unique_tools??0,unique_files:n?.unique_files??0,max_file_edits:r?.max_file_edits??0,has_commit:n?.has_commit??0,commit_message:o?.data??"",edit_test_cycles:c,duration_min:n?.duration_min??0,compact_count:s?.compact_count??0,sources_indexed:n?.sources_indexed??0,total_chunks:n?.total_chunks??0,search_queries:n?.search_queries??0}}incrementCompactCount(e){this.stmt(F.incrementCompactCount).run(e)}getUsageCursor(e){return this.stmt(F.getUsageCursor).get(e)?.usage_cursor??null}setUsageCursor(e,n){this.stmt(F.setUsageCursor).run(n,e)}upsertResume(e,n,r){this.stmt(F.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(F.getResume).get(e)??null}markResumeConsumed(e){this.stmt(F.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(F.claimLatestUnconsumedResume).get(e);return n?{sessionId:n.session_id,snapshot:n.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,n,r=0){let o=Number.isFinite(r)&&r>0?Math.round(r):0;try{this.stmt(F.incrementToolCall).run(e,n,o)}catch{}}getToolCallStats(e){try{let n=this.stmt(F.getToolCallTotals).get(e),r=this.stmt(F.getToolCallByTool).all(e),o={};for(let s of r)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:n?.calls??0,totalBytesReturned:n?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(F.deleteEvents).run(e),this.stmt(F.deleteResume).run(e),this.stmt(F.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(F.getOldSessions).all(n);for(let{session_id:o}of r)this.deleteSession(o);return r.length}pruneOrphanedEvents(){let e=this.db.prepare("DELETE FROM session_events WHERE session_id NOT IN (SELECT session_id FROM session_meta)").run();return Number(e.changes??0)}}});import{join as ls,resolve as wx}from"node:path";import{accessSync as EI,copyFileSync as TI,constants as $I,mkdirSync as PI}from"node:fs";import{homedir as ip}from"node:os";function ht(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?wx(ip(),e.replace(/^~[/\\]?/,"")):wx(e)}var ve,it=x(()=>{"use strict";Jt();ve=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=ht(),n=e?ls(e,"context-mode","sessions"):ls(ip(),...this.sessionDirSegments,"context-mode","sessions");return PI(n,{recursive:!0}),n}getConfigDir(e){return ls(ip(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=ht(),r=n?ls(n,"context-mode","memory"):ls(this.getConfigDir(),"memory");return e?ls(r,rt(e)):r}backupSettings(){let e=this.getSettingsPath();try{EI(e,$I.R_OK);let n=e+".bak";return TI(e,n),n}catch{return null}}}});var ds,ap=x(()=>{"use strict";it();ds=class extends ve{parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),e.updatedOutput&&(n.updatedMCPToolOutput=e.updatedOutput),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as cp}from"node:fs";import{join as up}from"node:path";async function RI(){if(ps)return ps;if(ms)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let n of t)try{let r=await import(n.href);if(typeof r?.assertPluginCacheIntegrity=="function")return ps=r,ps}catch(r){e=r}return ms=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return ms=t instanceof Error?t.message:String(t),null}}function CI(t){let e=[];return cp(up(t,"start.mjs"))||e.push("start.mjs"),!cp(up(t,"server.bundle.mjs"))&&!cp(up(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function Ex(t){if(ps){let e=ps.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(ms){let e=CI(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${ms}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${ms}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var ps,ms,Tx=x(()=>{"use strict";ps=null,ms=null;RI()});function Ii(t,e){let n=Qr[e],r=dp(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function dp(t,e){if(e){let n=Qr[t];return qe(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function pp(t){let e=bc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function Rx(t){let e=Object.values(Qr);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Xt,OI,lp,$x,II,UV,Qr,Px,FV,Cx=x(()=>{"use strict";Rn();Xt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},OI="mcp__",lp=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",OI],$x=lp.join("|"),II=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],UV=II.join("|"),Qr={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},Px=[Xt.PRE_TOOL_USE,Xt.SESSION_START],FV=[Xt.POST_TOOL_USE,Xt.PRE_COMPACT,Xt.USER_PROMPT_SUBMIT,Xt.STOP]});var fp={};_e(fp,{ClaudeCodeAdapter:()=>mp});import{readFileSync as Rc,writeFileSync as Ox,existsSync as Ix,readdirSync as AI,chmodSync as NI,accessSync as MI,mkdirSync as DI,constants as jI}from"node:fs";import{resolve as Cc,join as xr}from"node:path";import{homedir as Ax}from"node:os";var mp,hp=x(()=>{"use strict";ap();it();Sr();Tx();Rn();Cx();mp=class extends ds{constructor(){super([".claude"])}name="Claude Code";paradigm="json-stdio";projectDirEnvVar="CLAUDE_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getConfigDir(e){return Ze()}getSessionDir(){let e=ht(),n=e?xr(e,"context-mode","sessions"):xr(this.getConfigDir(),"context-mode","sessions");return DI(n,{recursive:!0}),n}getSettingsPath(){return xr(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=qe(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...lp].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=Rc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){Ox(this.getSettingsPath(),JSON.stringify(e,null,2)+`
147`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),n;let o=r.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,Xt.PRE_TOOL_USE);n.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,Xt.SESSION_START);return n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),n}getHealthChecks(e){let n=Object.entries(Qr).map(([o,s])=>{let i=xr(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>Ix(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>Ex(e)};return[...n,r]}readPluginHooks(e){let n=[xr(e,"hooks","hooks.json"),xr(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=Rc(r,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,n,r){let o=e?.[r];if(o&&o.length>0&&o.some(i=>Ii(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>Ii(i,r)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let n=e.enabledPlugins;if(!n)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let r=Object.keys(n).find(o=>o.startsWith("context-mode"));return r&&n[r]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${r}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let n=xr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Rc(n,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=Array.from(new Set([this.getConfigDir(),Ze(),Cc(Ax(),".claude"),Cc(Ax(),".config","claude")]));for(let n of e){let r=Cc(n,"plugins","cache","context-mode","context-mode");try{let s=AI(r).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let l=0;l<3;l++)if((c[l]??0)!==(u[l]??0))return(c[l]??0)-(u[l]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let u of Object.keys(r)){let l=r[u];if(!Array.isArray(l))continue;let d=l.filter(f=>{let m=f;if(!Rx(m))return!0;let h=m.hooks??[];return h.every(y=>!y.command||!pp(y.command))?!0:h.every(y=>{let _=y.command?pp(y.command):null;return _?Ix(_):!0})}),p=l.length-d.length;p>0&&(r[u]=d,o.push(`Removed ${p} stale ${u} hook(s)`))}let a=this.checkPluginRegistration().status==="pass"?this.readPluginHooks(e):void 0;if(a&&Px.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(Qr),d=p=>p!=null&&(l.some(f=>p.includes(f))||p.includes("context-mode hook"));for(let p of Object.keys(r)){let f=r[p];if(!Array.isArray(f))continue;let m=0;for(let g of f){let y=g,_=y.hooks??[],b=_.length;y.hooks=_.filter(S=>!d(S.command)),m+=b-y.hooks.length}let h=f.filter(g=>{let y=g.hooks;return Array.isArray(y)&&y.length>0});(m>0||h.length!==f.length)&&(r[p]=h,m>0&&o.push(`Removed ${m} duplicate ${p} hook(s) \u2014 covered by plugin hooks.json`))}return n.hooks=r,this.writeSettings(n),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let c=[Xt.PRE_TOOL_USE,Xt.SESSION_START];for(let u of c){let l=dp(u,e);if(u===Xt.PRE_TOOL_USE){let d={matcher:$x,hooks:[{type:"command",command:l}]},p=r.PreToolUse;if(p&&Array.isArray(p)){let f=p.findIndex(m=>Ii(m,u));f>=0?(p[f]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r.PreToolUse=p}else r.PreToolUse=[d],o.push(`Created ${u} hooks section`)}else{let d={matcher:"",hooks:[{type:"command",command:l}]},p=r[u];if(p&&Array.isArray(p)){let f=p.findIndex(m=>Ii(m,u));f>=0?(p[f]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r[u]=p}else r[u]=[d],o.push(`Created ${u} hooks section`)}}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[];for(let[,r]of Object.entries(Qr)){let o=Cc(e,"hooks",r);try{MI(o,jI.R_OK),NI(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=xr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Rc(r,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=n,a.lastUpdated=new Date().toISOString();Ox(r,JSON.stringify(o,null,2)+`

Callers 15

bulkInsertEventsMethod · 0.45
JPFunction · 0.45
XPFunction · 0.45
YPFunction · 0.45
search.test.tsFile · 0.45
server.test.tsFile · 0.45
kimi.test.tsFile · 0.45
codex.test.tsFile · 0.45

Calls 15

RiFunction · 0.85
EcFunction · 0.85
updateMethod · 0.80
fFunction · 0.70
getMethod · 0.65
runMethod · 0.65
toUpperCaseMethod · 0.45
trimMethod · 0.45
_getSessionProjectDirMethod · 0.45
isFiniteMethod · 0.45
maxMethod · 0.45
minMethod · 0.45

Tested by

no test coverage detected