From 3869b083d07960a6a7434720321d88275ecfd0b8 Mon Sep 17 00:00:00 2001 From: Alex Newman Date: Thu, 16 Apr 2026 17:16:51 -0700 Subject: [PATCH] fix(context): derive project from explicit projects array, not cwd MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a caller (e.g. worker context-inject route) passes a `projects` array without a matching cwd, the cwd-derived `context.primary` drifted from the projects being queried — producing an empty-state header for one project while querying another. Use the last entry of `projects` so header and query target stay in sync. --- plugin/scripts/context-generator.cjs | 2 +- plugin/scripts/worker-service.cjs | 2 +- src/services/context/ContextBuilder.ts | 7 +++++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/plugin/scripts/context-generator.cjs b/plugin/scripts/context-generator.cjs index f4264238..46141211 100644 --- a/plugin/scripts/context-generator.cjs +++ b/plugin/scripts/context-generator.cjs @@ -756,4 +756,4 @@ ${c.gray}${"\u2500".repeat(60)}${c.reset} ${c.dim}No previous sessions found for this project yet.${c.reset} `}function lt(r,e,t,s){let n=[];return s?n.push(...tt(r)):n.push(...je(r)),s?n.push(...st()):n.push(...Xe()),s?n.push(...rt()):n.push(...Ge()),s?n.push(...nt()):n.push(...Be()),q(t)&&(s?n.push(...ot(e,t)):n.push(...We(e,t))),n}var me=L(require("path"),1);function z(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return _.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e),[]}}function _e(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function pe(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function gt(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function Et(r,e){return me.default.isAbsolute(r)?me.default.relative(e,r):r}function Tt(r,e,t){let s=z(r);if(s.length>0)return Et(s[0],e);if(t){let n=z(t);if(n.length>0)return Et(n[0],e)}return"General"}function Yt(r){let e=new Map;for(let s of r){let n=s.type==="observation"?s.data.created_at:s.data.displayTime,o=gt(n);e.has(o)||e.set(o,[]),e.get(o).push(s)}let t=Array.from(e.entries()).sort((s,n)=>{let o=new Date(s[0]).getTime(),i=new Date(n[0]).getTime();return o-i});return new Map(t)}function ft(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?z(r.facts).join(` `):null}function qt(r,e,t,s){let n=[];n.push(...Ye(r));let o="";for(let i of e)if(i.type==="summary"){let a=i.data,d=_e(a.displayTime);n.push(...Je(a,d))}else{let a=i.data,d=pe(a.created_at),m=d!==o?d:"";if(o=d,t.has(a.id)){let E=ft(a,s);n.push(...Ke(a,m,E,s))}else n.push(Ve(a,m,s))}return n}function Vt(r,e,t,s,n){let o=[];o.push(...it(r));let i=null,a="";for(let d of e)if(d.type==="summary"){i=null,a="";let u=d.data,m=_e(u.displayTime);o.push(...ut(u,m))}else{let u=d.data,m=Tt(u.files_modified,n,u.files_read),l=pe(u.created_at),E=l!==a;a=l;let T=t.has(u.id);if(m!==i&&(o.push(...at(m)),i=m),T){let O=ft(u,s);o.push(...ct(u,l,E,O,s))}else o.push(dt(u,l,E,s))}return o.push(""),o}function Kt(r,e,t,s,n,o){return o?Vt(r,e,t,s,n):qt(r,e,t,s)}function St(r,e,t,s,n){let o=[],i=Yt(r);for(let[a,d]of i)o.push(...Kt(a,d,e,t,s,n));return o}function bt(r,e,t){return!(!r.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||t&&e.created_at_epoch<=t.created_at_epoch)}function ht(r,e){let t=[];return e?(t.push(...F("Investigated",r.investigated,c.blue)),t.push(...F("Learned",r.learned,c.yellow)),t.push(...F("Completed",r.completed,c.green)),t.push(...F("Next Steps",r.next_steps,c.magenta))):(t.push(...$("Investigated",r.investigated)),t.push(...$("Learned",r.learned)),t.push(...$("Completed",r.completed)),t.push(...$("Next Steps",r.next_steps))),t}function Ot(r,e){return e?mt(r):ze(r)}function At(r,e,t){return!q(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?_t(r.totalDiscoveryTokens,r.totalReadTokens):Qe(r.totalDiscoveryTokens,r.totalReadTokens)}var Jt=Rt.default.join((0,Nt.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function zt(){try{return new X}catch(r){if(r.code==="ERR_DLOPEN_FAILED"){try{(0,Ct.unlinkSync)(Jt)}catch(e){_.debug("SYSTEM","Marker file cleanup failed (may not exist)",{},e)}return _.error("SYSTEM","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function Qt(r,e){return e?pt(r):Ze(r)}function Zt(r,e,t,s,n,o,i){let a=[],d=ie(e);a.push(...lt(r,d,s,i));let u=t.slice(0,s.sessionCount),m=we(u,t),l=ue(e,m),E=Pe(e,s.fullObservationCount);a.push(...St(l,E,s,n,i));let T=t[0],O=e[0];bt(s,T,O)&&a.push(...ht(T,i));let S=ce(e,s,o,n);return a.push(...Ot(S,i)),a.push(...At(d,s,i)),a.join(` -`).trimEnd()}async function le(r,e=!1){let t=re(),s=r?.cwd??process.cwd(),n=De(s),o=n.primary,i=r?.platform_source,a=r?.projects??n.allProjects;r?.full&&(t.totalObservationCount=999999,t.sessionCount=999999);let d=zt();if(!d)return"";try{let u=a.length>1?$e(d,a,t,i):ae(d,o,t,i),m=a.length>1?Fe(d,a,t,i):de(d,o,t,i);return u.length===0&&m.length===0?Qt(o,e):Zt(o,u,m,t,s,r?.session_id,e)}finally{d.close()}}0&&(module.exports={generateContext}); +`).trimEnd()}async function le(r,e=!1){let t=re(),s=r?.cwd??process.cwd(),n=De(s),o=r?.platform_source,i=r?.projects??n.allProjects,a=i[i.length-1];r?.full&&(t.totalObservationCount=999999,t.sessionCount=999999);let d=zt();if(!d)return"";try{let u=i.length>1?$e(d,i,t,o):ae(d,a,t,o),m=i.length>1?Fe(d,i,t,o):de(d,a,t,o);return u.length===0&&m.length===0?Qt(a,e):Zt(a,u,m,t,s,r?.session_id,e)}finally{d.close()}}0&&(module.exports={generateContext}); diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index 3590ff6e..ac52fbe8 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -948,7 +948,7 @@ ${Y.gray}${"\u2500".repeat(60)}${Y.reset} ${Y.dim}No previous sessions found for this project yet.${Y.reset} `}var cl=he(()=>{"use strict";Um();en();qa()});function QH(t,e,r,n){let i=[];return n?i.push(...UH(t)):i.push(...TH(t)),n?i.push(...FH()):i.push(...$H()),n?i.push(...qH()):i.push(...IH()),n?i.push(...HH()):i.push(...RH()),i_(r)&&(n?i.push(...ZH(e,r)):i.push(...OH(e,r))),i}var e5=he(()=>{"use strict";qa();al();cl()});function nxe(t){let e=new Map;for(let n of t){let i=n.type==="observation"?n.data.created_at:n.data.displayTime,s=Ms(i);e.has(s)||e.set(s,[]),e.get(s).push(n)}let r=Array.from(e.entries()).sort((n,i)=>{let s=new Date(n[0]).getTime(),o=new Date(i[0]).getTime();return s-o});return new Map(r)}function t5(t,e){return e.fullObservationField==="narrative"?t.narrative:t.facts?Ia(t.facts).join(` `):null}function ixe(t,e,r,n){let i=[];i.push(...CH(t));let s="";for(let o of e)if(o.type==="summary"){let a=o.data,c=Nn(a.displayTime);i.push(...MH(a,c))}else{let a=o.data,c=vr(a.created_at),l=c!==s?c:"";if(s=c,r.has(a.id)){let p=t5(a,n);i.push(...NH(a,l,p,n))}else i.push(AH(a,l,n))}return i}function sxe(t,e,r,n,i){let s=[];s.push(...BH(t));let o=null,a="";for(let c of e)if(c.type==="summary"){o=null,a="";let u=c.data,l=Nn(u.displayTime);s.push(...KH(u,l))}else{let u=c.data,l=Ti(u.files_modified,i,u.files_read),d=vr(u.created_at),p=d!==a;a=d;let m=r.has(u.id);if(l!==o&&(s.push(...GH(l)),o=l),m){let f=t5(u,n);s.push(...VH(u,d,p,f,n))}else s.push(WH(u,d,p,n))}return s.push(""),s}function oxe(t,e,r,n,i,s){return s?sxe(t,e,r,n,i):ixe(t,e,r,n)}function r5(t,e,r,n,i){let s=[],o=nxe(t);for(let[a,c]of o)s.push(...oxe(a,c,e,r,n,i));return s}var n5=he(()=>{"use strict";zs();al();cl()});function i5(t,e,r){return!(!t.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||r&&e.created_at_epoch<=r.created_at_epoch)}function s5(t,e){let r=[];return e?(r.push(...Hm("Investigated",t.investigated,Y.blue)),r.push(...Hm("Learned",t.learned,Y.yellow)),r.push(...Hm("Completed",t.completed,Y.green)),r.push(...Hm("Next Steps",t.next_steps,Y.magenta))):(r.push(...qm("Investigated",t.investigated)),r.push(...qm("Learned",t.learned)),r.push(...qm("Completed",t.completed)),r.push(...qm("Next Steps",t.next_steps))),r}var o5=he(()=>{"use strict";Um();al();cl()});function a5(t,e){return e?JH(t):DH(t)}function c5(t,e,r){return!i_(e)||t.totalDiscoveryTokens<=0||t.savings<=0?[]:r?XH(t.totalDiscoveryTokens,t.totalReadTokens):jH(t.totalDiscoveryTokens,t.totalReadTokens)}var u5=he(()=>{"use strict";qa();al();cl()});function cxe(){try{return new Os}catch(t){if(t.code==="ERR_DLOPEN_FAILED"){try{(0,p5.unlinkSync)(axe)}catch(e){_.debug("SYSTEM","Marker file cleanup failed (may not exist)",{},e)}return _.error("SYSTEM","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw t}}function uxe(t,e){return e?YH(t):zH(t)}function lxe(t,e,r,n,i,s,o){let a=[],c=HI(e);a.push(...QH(t,c,n,o));let u=r.slice(0,n.sessionCount),l=wH(u,r),d=WI(e,l),p=EH(e,n.fullObservationCount);a.push(...r5(d,p,n,i,o));let m=r[0],f=e[0];i5(n,m,f)&&a.push(...s5(m,o));let h=GI(e,n,s,i);return a.push(...a5(h,o)),a.push(...c5(c,n,o)),a.join(` -`).trimEnd()}async function KI(t,e=!1){let r=LI(),n=t?.cwd??process.cwd(),i=zn(n),s=i.primary,o=t?.platform_source,a=t?.projects??i.allProjects;t?.full&&(r.totalObservationCount=999999,r.sessionCount=999999);let c=cxe();if(!c)return"";try{let u=a.length>1?SH(c,a,r,o):ZI(c,s,r,o),l=a.length>1?xH(c,a,r,o):BI(c,s,r,o);return u.length===0&&l.length===0?uxe(s,e):lxe(s,u,l,r,n,t?.session_id,e)}finally{c.close()}}var l5,d5,p5,axe,m5=he(()=>{"use strict";l5=Oe(require("path"),1),d5=require("os"),p5=require("fs");pg();Q();Fa();UI();qa();VI();e5();n5();o5();u5();al();cl();axe=l5.default.join((0,d5.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version")});var f5=he(()=>{"use strict";m5();UI();qa();VI()});var JI={};cn(JI,{generateContext:()=>KI});var XI=he(()=>{"use strict";f5()});function hxe(){try{let t=process.stdin;return t.isTTY?!1:(t.readable,!0)}catch{return!1}}function gxe(t){let e=t.trim();if(!e)return{success:!1};try{return{success:!0,value:JSON.parse(e)}}catch{return{success:!1}}}async function S5(){if(hxe())return new Promise((t,e)=>{let r="",n=!1,i=null,s=()=>{try{process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),process.stdin.removeAllListeners("error")}catch{}},o=l=>{n||(n=!0,i&&clearTimeout(i),clearTimeout(u),s(),t(l))},a=l=>{n||(n=!0,i&&clearTimeout(i),clearTimeout(u),s(),e(l))},c=()=>{let l=gxe(r);return l.success?(o(l.value),!0):!1},u=setTimeout(()=>{n||c()||(r.trim()?a(new Error(`Incomplete JSON after ${b5}ms: ${r.slice(0,100)}...`)):o(void 0))},b5);try{process.stdin.on("data",l=>{r+=l,i&&(clearTimeout(i),i=null),!c()&&(i=setTimeout(()=>{c()},vxe))}),process.stdin.on("end",()=>{n||c()||o((r.trim(),void 0))}),process.stdin.on("error",()=>{n||o(void 0)})}catch{n=!0,clearTimeout(u),s(),t(void 0)}})}var b5,vxe,x5=he(()=>{"use strict";b5=3e4,vxe=50});var w5,E5=he(()=>{"use strict";w5={normalizeInput(t){let e=t??{};return{sessionId:e.session_id??e.id??e.sessionId,cwd:e.cwd??process.cwd(),prompt:e.prompt,toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response,transcriptPath:e.transcript_path}},formatOutput(t){let e=t??{};if(e.hookSpecificOutput){let n={hookSpecificOutput:t.hookSpecificOutput};return e.systemMessage&&(n.systemMessage=e.systemMessage),n}let r={};return e.systemMessage&&(r.systemMessage=e.systemMessage),r}}});var k5,T5=he(()=>{"use strict";k5={normalizeInput(t){let e=t??{},r=!!e.command&&!e.tool_name;return{sessionId:e.conversation_id||e.generation_id||e.id,cwd:e.workspace_roots?.[0]??e.cwd??process.cwd(),prompt:e.prompt??e.query??e.input??e.message,toolName:r?"Bash":e.tool_name,toolInput:r?{command:e.command}:e.tool_input,toolResponse:r?{output:e.output}:e.result_json,transcriptPath:void 0,filePath:e.file_path,edits:e.edits}},formatOutput(t){return{continue:t.continue??!0}}}});var $5,I5=he(()=>{"use strict";$5={normalizeInput(t){let e=t??{},r=e.cwd??process.env.GEMINI_CWD??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd(),n=e.session_id??process.env.GEMINI_SESSION_ID??void 0,i=e.hook_event_name,s=e.tool_name,o=e.tool_input,a=e.tool_response;i==="AfterAgent"&&e.prompt_response&&(s=s??"GeminiAgent",o=o??{prompt:e.prompt},a=a??{response:e.prompt_response}),i==="BeforeTool"&&s&&!a&&(a={_preExecution:!0}),i==="Notification"&&(s=s??"GeminiNotification",o=o??{notification_type:e.notification_type,message:e.message},a=a??{details:e.details});let c={};return e.source&&(c.source=e.source),e.reason&&(c.reason=e.reason),e.trigger&&(c.trigger=e.trigger),e.mcp_context&&(c.mcp_context=e.mcp_context),e.notification_type&&(c.notification_type=e.notification_type),e.stop_hook_active!==void 0&&(c.stop_hook_active=e.stop_hook_active),e.original_request_name&&(c.original_request_name=e.original_request_name),i&&(c.hook_event_name=i),{sessionId:n,cwd:r,prompt:e.prompt,toolName:s,toolInput:o,toolResponse:a,transcriptPath:e.transcript_path,metadata:Object.keys(c).length>0?c:void 0}},formatOutput(t){let e={};if(e.continue=t.continue??!0,t.suppressOutput!==void 0&&(e.suppressOutput=t.suppressOutput),t.systemMessage){let r=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;e.systemMessage=t.systemMessage.replace(r,"")}return t.hookSpecificOutput&&(e.hookSpecificOutput={additionalContext:t.hookSpecificOutput.additionalContext}),e}}});var nR,R5=he(()=>{"use strict";nR={normalizeInput(t){let e=t;return{sessionId:e.sessionId??e.session_id??"unknown",cwd:e.cwd??process.cwd(),prompt:e.prompt,toolName:e.toolName??e.tool_name,toolInput:e.toolInput??e.tool_input,toolResponse:e.toolResponse??e.tool_response,transcriptPath:e.transcriptPath??e.transcript_path,filePath:e.filePath??e.file_path,edits:e.edits}},formatOutput(t){return t}}});var O5,C5=he(()=>{"use strict";O5={normalizeInput(t){let e=t??{},r=e.tool_info??{},n=e.agent_action_name??"",i={sessionId:e.trajectory_id??e.execution_id,cwd:r.cwd??process.cwd(),platform:"windsurf"};switch(n){case"pre_user_prompt":return{...i,prompt:r.user_prompt};case"post_write_code":return{...i,toolName:"Write",filePath:r.file_path,edits:r.edits,toolInput:{file_path:r.file_path,edits:r.edits}};case"post_run_command":return{...i,cwd:r.cwd??i.cwd,toolName:"Bash",toolInput:{command:r.command_line}};case"post_mcp_tool_use":return{...i,toolName:r.mcp_tool_name??"mcp_tool",toolInput:r.mcp_tool_arguments,toolResponse:r.mcp_result};case"post_cascade_response":return{...i,toolName:"cascade_response",toolResponse:r.response};default:return i}},formatOutput(t){return{continue:t.continue??!0}}}});function P5(t){switch(t){case"claude-code":return w5;case"cursor":return k5;case"gemini":case"gemini-cli":return $5;case"windsurf":return O5;case"raw":return nR;default:return nR}}var A5=he(()=>{"use strict";E5();T5();I5();R5();C5()});var iR,sR=he(()=>{"use strict";Rr();Fa();fn();Q();Yt();$t();_i();iR={async execute(t){if(!await or())return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:""},exitCode:nt.SUCCESS};let r=t.cwd??process.cwd(),n=zn(r),i=Xr(),s=bt(t.platform),a=ge.loadFromFile(lt).CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT==="true",c=n.allProjects.join(","),u=`/api/context/inject?projects=${encodeURIComponent(c)}&platformSource=${encodeURIComponent(s)}`,l=t.platform==="claude-code"?`${u}&colors=true`:u;try{let[d,p]=await Promise.all([ct(u),a?ct(l).catch(()=>null):Promise.resolve(null)]);if(!d.ok)return _.warn("HOOK","Context generation failed, returning empty",{status:d.status}),{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:""},exitCode:nt.SUCCESS};let[m,f]=await Promise.all([d.text(),p?.ok?p.text():Promise.resolve("")]),h=m.trim(),g=f.trim(),v=t.platform,y=g||(v==="gemini-cli"||v==="gemini"?h:""),b=a&&y?`${y} +`).trimEnd()}async function KI(t,e=!1){let r=LI(),n=t?.cwd??process.cwd(),i=zn(n),s=t?.platform_source,o=t?.projects??i.allProjects,a=o[o.length-1];t?.full&&(r.totalObservationCount=999999,r.sessionCount=999999);let c=cxe();if(!c)return"";try{let u=o.length>1?SH(c,o,r,s):ZI(c,a,r,s),l=o.length>1?xH(c,o,r,s):BI(c,a,r,s);return u.length===0&&l.length===0?uxe(a,e):lxe(a,u,l,r,n,t?.session_id,e)}finally{c.close()}}var l5,d5,p5,axe,m5=he(()=>{"use strict";l5=Oe(require("path"),1),d5=require("os"),p5=require("fs");pg();Q();Fa();UI();qa();VI();e5();n5();o5();u5();al();cl();axe=l5.default.join((0,d5.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version")});var f5=he(()=>{"use strict";m5();UI();qa();VI()});var JI={};cn(JI,{generateContext:()=>KI});var XI=he(()=>{"use strict";f5()});function hxe(){try{let t=process.stdin;return t.isTTY?!1:(t.readable,!0)}catch{return!1}}function gxe(t){let e=t.trim();if(!e)return{success:!1};try{return{success:!0,value:JSON.parse(e)}}catch{return{success:!1}}}async function S5(){if(hxe())return new Promise((t,e)=>{let r="",n=!1,i=null,s=()=>{try{process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),process.stdin.removeAllListeners("error")}catch{}},o=l=>{n||(n=!0,i&&clearTimeout(i),clearTimeout(u),s(),t(l))},a=l=>{n||(n=!0,i&&clearTimeout(i),clearTimeout(u),s(),e(l))},c=()=>{let l=gxe(r);return l.success?(o(l.value),!0):!1},u=setTimeout(()=>{n||c()||(r.trim()?a(new Error(`Incomplete JSON after ${b5}ms: ${r.slice(0,100)}...`)):o(void 0))},b5);try{process.stdin.on("data",l=>{r+=l,i&&(clearTimeout(i),i=null),!c()&&(i=setTimeout(()=>{c()},vxe))}),process.stdin.on("end",()=>{n||c()||o((r.trim(),void 0))}),process.stdin.on("error",()=>{n||o(void 0)})}catch{n=!0,clearTimeout(u),s(),t(void 0)}})}var b5,vxe,x5=he(()=>{"use strict";b5=3e4,vxe=50});var w5,E5=he(()=>{"use strict";w5={normalizeInput(t){let e=t??{};return{sessionId:e.session_id??e.id??e.sessionId,cwd:e.cwd??process.cwd(),prompt:e.prompt,toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response,transcriptPath:e.transcript_path}},formatOutput(t){let e=t??{};if(e.hookSpecificOutput){let n={hookSpecificOutput:t.hookSpecificOutput};return e.systemMessage&&(n.systemMessage=e.systemMessage),n}let r={};return e.systemMessage&&(r.systemMessage=e.systemMessage),r}}});var k5,T5=he(()=>{"use strict";k5={normalizeInput(t){let e=t??{},r=!!e.command&&!e.tool_name;return{sessionId:e.conversation_id||e.generation_id||e.id,cwd:e.workspace_roots?.[0]??e.cwd??process.cwd(),prompt:e.prompt??e.query??e.input??e.message,toolName:r?"Bash":e.tool_name,toolInput:r?{command:e.command}:e.tool_input,toolResponse:r?{output:e.output}:e.result_json,transcriptPath:void 0,filePath:e.file_path,edits:e.edits}},formatOutput(t){return{continue:t.continue??!0}}}});var $5,I5=he(()=>{"use strict";$5={normalizeInput(t){let e=t??{},r=e.cwd??process.env.GEMINI_CWD??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd(),n=e.session_id??process.env.GEMINI_SESSION_ID??void 0,i=e.hook_event_name,s=e.tool_name,o=e.tool_input,a=e.tool_response;i==="AfterAgent"&&e.prompt_response&&(s=s??"GeminiAgent",o=o??{prompt:e.prompt},a=a??{response:e.prompt_response}),i==="BeforeTool"&&s&&!a&&(a={_preExecution:!0}),i==="Notification"&&(s=s??"GeminiNotification",o=o??{notification_type:e.notification_type,message:e.message},a=a??{details:e.details});let c={};return e.source&&(c.source=e.source),e.reason&&(c.reason=e.reason),e.trigger&&(c.trigger=e.trigger),e.mcp_context&&(c.mcp_context=e.mcp_context),e.notification_type&&(c.notification_type=e.notification_type),e.stop_hook_active!==void 0&&(c.stop_hook_active=e.stop_hook_active),e.original_request_name&&(c.original_request_name=e.original_request_name),i&&(c.hook_event_name=i),{sessionId:n,cwd:r,prompt:e.prompt,toolName:s,toolInput:o,toolResponse:a,transcriptPath:e.transcript_path,metadata:Object.keys(c).length>0?c:void 0}},formatOutput(t){let e={};if(e.continue=t.continue??!0,t.suppressOutput!==void 0&&(e.suppressOutput=t.suppressOutput),t.systemMessage){let r=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;e.systemMessage=t.systemMessage.replace(r,"")}return t.hookSpecificOutput&&(e.hookSpecificOutput={additionalContext:t.hookSpecificOutput.additionalContext}),e}}});var nR,R5=he(()=>{"use strict";nR={normalizeInput(t){let e=t;return{sessionId:e.sessionId??e.session_id??"unknown",cwd:e.cwd??process.cwd(),prompt:e.prompt,toolName:e.toolName??e.tool_name,toolInput:e.toolInput??e.tool_input,toolResponse:e.toolResponse??e.tool_response,transcriptPath:e.transcriptPath??e.transcript_path,filePath:e.filePath??e.file_path,edits:e.edits}},formatOutput(t){return t}}});var O5,C5=he(()=>{"use strict";O5={normalizeInput(t){let e=t??{},r=e.tool_info??{},n=e.agent_action_name??"",i={sessionId:e.trajectory_id??e.execution_id,cwd:r.cwd??process.cwd(),platform:"windsurf"};switch(n){case"pre_user_prompt":return{...i,prompt:r.user_prompt};case"post_write_code":return{...i,toolName:"Write",filePath:r.file_path,edits:r.edits,toolInput:{file_path:r.file_path,edits:r.edits}};case"post_run_command":return{...i,cwd:r.cwd??i.cwd,toolName:"Bash",toolInput:{command:r.command_line}};case"post_mcp_tool_use":return{...i,toolName:r.mcp_tool_name??"mcp_tool",toolInput:r.mcp_tool_arguments,toolResponse:r.mcp_result};case"post_cascade_response":return{...i,toolName:"cascade_response",toolResponse:r.response};default:return i}},formatOutput(t){return{continue:t.continue??!0}}}});function P5(t){switch(t){case"claude-code":return w5;case"cursor":return k5;case"gemini":case"gemini-cli":return $5;case"windsurf":return O5;case"raw":return nR;default:return nR}}var A5=he(()=>{"use strict";E5();T5();I5();R5();C5()});var iR,sR=he(()=>{"use strict";Rr();Fa();fn();Q();Yt();$t();_i();iR={async execute(t){if(!await or())return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:""},exitCode:nt.SUCCESS};let r=t.cwd??process.cwd(),n=zn(r),i=Xr(),s=bt(t.platform),a=ge.loadFromFile(lt).CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT==="true",c=n.allProjects.join(","),u=`/api/context/inject?projects=${encodeURIComponent(c)}&platformSource=${encodeURIComponent(s)}`,l=t.platform==="claude-code"?`${u}&colors=true`:u;try{let[d,p]=await Promise.all([ct(u),a?ct(l).catch(()=>null):Promise.resolve(null)]);if(!d.ok)return _.warn("HOOK","Context generation failed, returning empty",{status:d.status}),{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:""},exitCode:nt.SUCCESS};let[m,f]=await Promise.all([d.text(),p?.ok?p.text():Promise.resolve("")]),h=m.trim(),g=f.trim(),v=t.platform,y=g||(v==="gemini-cli"||v==="gemini"?h:""),b=a&&y?`${y} View Observations Live @ http://localhost:${i}`:void 0;return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:h},systemMessage:b}}catch(d){return _.warn("HOOK","Context fetch error, returning empty",{error:d instanceof Error?d.message:String(d)}),{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:""},exitCode:nt.SUCCESS}}}}});function yxe(t){try{let e=JSON.parse(t);if(e&&Array.isArray(e.messages))return{isGemini:!0,messages:e.messages}}catch{}return{isGemini:!1}}function N5(t,e,r=!1){if(!t||!(0,b_.existsSync)(t))return _.warn("PARSER",`Transcript path missing or file does not exist: ${t}`),"";let n=(0,b_.readFileSync)(t,"utf-8").trim();if(!n)return _.warn("PARSER",`Transcript file exists but is empty: ${t}`),"";let i=yxe(n);return i.isGemini?_xe(i.messages,e,r):bxe(n,e,r)}function _xe(t,e,r){let n=e==="assistant"?"gemini":"user";for(let i=t.length-1;i>=0;i--){let s=t[i];if(s?.type===n&&typeof s.content=="string"){let o=s.content;return r&&(o=o.replace(sl,""),o=o.replace(/\n{3,}/g,` diff --git a/src/services/context/ContextBuilder.ts b/src/services/context/ContextBuilder.ts index 34b36de0..8190dc9a 100644 --- a/src/services/context/ContextBuilder.ts +++ b/src/services/context/ContextBuilder.ts @@ -130,11 +130,14 @@ export async function generateContext( const config = loadContextConfig(); const cwd = input?.cwd ?? process.cwd(); const context = getProjectContext(cwd); - const project = context.primary; const platformSource = input?.platform_source; - // Use provided projects array (for worktree support) or fall back to all known projects + // Single source of truth: explicit projects override cwd-derived context. + // `project` (used for header + single-project query) is always the last entry + // of `projects` so the empty-state header and the query target stay in sync + // when a caller passes `projects` without a matching cwd (e.g. worker route). const projects = input?.projects ?? context.allProjects; + const project = projects[projects.length - 1]; // Full mode: fetch all observations but keep normal rendering (level 1 summaries) if (input?.full) {