import{writeFileSync as j}from"node:fs";function w(G){let _={},H="";for(let V of G){if(V.category==="prompt"){H=V.data;continue}if(!_[V.category])_[V.category]=[];_[V.category].push(V)}let J=new Set;for(let V of _.file||[]){let L=(V.data.includes(" in ")?V.data.split(" in ").pop():V.data)?.split(/[/\\]/).pop()?.trim();if(L&&!L.includes("*"))J.add(L)}return{grouped:_,lastPrompt:H,fileNames:J}}function M(G,_){let{grouped:H,lastPrompt:J,fileNames:V}=w(G),z=[];if(z.push("# Session Resume"),z.push(""),z.push(`Events: ${G.length} | Timestamp: ${new Date().toISOString()}`),z.push(""),V.size>0){z.push("## Active Files"),z.push("");for(let L of V)z.push(`- ${L}`);z.push("")}if(H.rule?.length>0){z.push("## Project Rules"),z.push("");for(let L of H.rule)if(L.type==="rule_content"){let B=L.data.replace(/^(#{1,3}) /gm,($,K)=>"#".repeat(K.length+3)+" ");z.push(B),z.push("")}else z.push(`- ${L.data}`);z.push("")}if(H.task?.length>0){let L=[],B={};for(let U of H.task)try{let Y=JSON.parse(U.data);if(Y.subject)L.push(Y.subject);else if(Y.taskId&&Y.status)B[Y.taskId]=Y.status}catch{L.push(U.data)}let $=new Set(["completed","deleted","failed"]),K=Object.keys(B).sort((U,Y)=>Number(U)-Number(Y)),Q=[],X=[];for(let U=0;U<L.length;U++){let Y=K[U],Z=Y?B[Y]||"pending":"pending";if($.has(Z))X.push(L[U]);else Q.push(L[U])}if(Q.length>0){z.push("## Tasks In Progress"),z.push("");for(let U of Q)z.push(`- ${U}`);z.push("")}if(X.length>0){z.push("## Tasks Completed"),z.push("");for(let U of X)z.push(`- ${U}`);z.push("")}}if(H.decision?.length>0){z.push("## User Decisions"),z.push("");for(let L of H.decision)z.push(`- ${L.data}`);z.push("")}if(H.git?.length>0){z.push("## Git Operations"),z.push("");for(let L of H.git)z.push(`- ${L.data}`);z.push("")}if(H.env?.length>0||H.cwd?.length>0){if(z.push("## Environment"),z.push(""),H.cwd?.length>0)z.push(`- cwd: ${H.cwd[H.cwd.length-1].data}`);for(let L of H.env||[])z.push(`- ${L.data}`);z.push("")}if(H.error?.length>0){z.push("## Errors Encountered"),z.push("");for(let L of H.error)z.push(`- ${L.data}`);z.push("")}if(H.mcp?.length>0){let L={};for(let B of H.mcp){let $=B.data.split(":")[0].trim();L[$]=(L[$]||0)+1}z.push("## MCP Tool Usage"),z.push("");for(let[B,$]of Object.entries(L))z.push(`- ${B}: ${$} calls`);z.push("")}if(H.subagent?.length>0){z.push("## Subagent Tasks"),z.push("");for(let L of H.subagent)z.push(`- ${L.data}`);z.push("")}if(H.skill?.length>0){let L=new Set(H.skill.map((B)=>B.data));z.push("## Active Skills"),z.push(""),z.push(`- ${[...L].join(", ")}`),z.push("")}if(H.intent?.length>0)z.push("## Session Intent"),z.push(""),z.push(`- ${H.intent[H.intent.length-1].data}`),z.push("");if(H.role?.length>0)z.push("## User Role"),z.push(""),z.push(`- ${H.role[H.role.length-1].data}`),z.push("");if(H.data?.length>0){z.push("## Data References"),z.push("");for(let L of H.data)z.push(`- ${L.data}`);z.push("")}if(H.plan?.length>0){let L=H.plan.some((Q)=>Q.type==="plan_approved"),B=H.plan.some((Q)=>Q.type==="plan_rejected"),$=H.plan[H.plan.length-1],K=$.type==="plan_enter"||$.type==="plan_file_write";if(z.push("## Plan Mode"),z.push(""),L)z.push("- Status: APPROVED AND EXECUTED");else if(B)z.push("- Status: REJECTED BY USER");else if(K)z.push("- Status: ACTIVE (in planning)");else z.push("- Status: COMPLETED");for(let Q of H.plan)z.push(`- ${Q.data}`);z.push("")}if(J)z.push("## Last User Prompt"),z.push(""),z.push(J),z.push("");return j(_,z.join(`
`),"utf-8"),{grouped:H,lastPrompt:J,fileNames:V}}function R(G,_,H){let{grouped:J,lastPrompt:V,fileNames:z}=_,L=G==="compact",B=`
<session_knowledge source="${L?"compact":"continue"}">`;if(B+=`
<session_guide>`,V){let K=V.length>300?V.substring(0,297)+"...":V;B+=`
## Last Request`,B+=`
${K}`,B+=`
`}if(J.task?.length>0){let K=[],Q={};for(let X of J.task)try{let U=JSON.parse(X.data);if(U.subject)K.push(U.subject);else if(U.taskId&&U.status)Q[U.taskId]=U.status}catch{}if(K.length>0){let X=new Set(["completed","deleted","failed"]),U=Object.keys(Q).sort((Z,T)=>Number(Z)-Number(T)),Y=[];for(let Z=0;Z<K.length;Z++){let T=U[Z],W=T?Q[T]||"pending":"pending";if(!X.has(W))Y.push(K[Z])}if(Y.length>0){B+=`
## Pending Tasks`;for(let Z of Y)B+=`
- ${Z}`;B+=`
`}}}if(J.decision?.length>0){B+=`
## Key Decisions`;for(let K of J.decision){let Q=K.data.length>150?K.data.substring(0,147)+"...":K.data;B+=`
- ${Q}`}B+=`
`}if(z.size>0)B+=`
## Files Modified`,B+=`
${[...z].join(", ")}`,B+=`
`;if(J.error?.length>0){B+=`
## Unresolved Errors`;for(let K of J.error){let Q=K.data.length>150?K.data.substring(0,147)+"...":K.data;B+=`
- ${Q}`}B+=`
`}if(J.git?.length>0){let K=[...new Set(J.git.map((Q)=>Q.data))];B+=`
## Git`,B+=`
${K.join(", ")}`,B+=`
`}if(J.rule?.length>0){let K=J.rule.filter((X)=>X.type!=="rule_content").map((X)=>{return X.data.split(/[/\\]/).slice(-2).join("/")}),Q=[...new Set(K)];if(Q.length>0)B+=`
## Project Rules`,B+=`
${Q.join(", ")}`,B+=`
`}if(J.mcp?.length>0){let K={};for(let Q of J.mcp){let X=Q.data.split(":")[0].trim();K[X]=(K[X]||0)+1}B+=`
## MCP Tools Used`,B+=`
${Object.entries(K).map(([Q,X])=>`${Q}(${X})`).join(", ")}`,B+=`
`}if(J.subagent?.length>0){B+=`
## Subagent Tasks`;for(let K of J.subagent){let Q=K.data.length>120?K.data.substring(0,117)+"...":K.data;B+=`
- ${Q}`}B+=`
`}if(J.skill?.length>0){let K=[...new Set(J.skill.map((Q)=>Q.data))];B+=`
## Skills Used`,B+=`
${K.join(", ")}`,B+=`
`}if(J.env?.length>0||J.cwd?.length>0){if(B+=`
## Environment`,J.cwd?.length>0)B+=`
cwd: ${J.cwd[J.cwd.length-1].data}`;for(let K of J.env||[])B+=`
${K.data}`;B+=`
`}if(J.data?.length>0){B+=`
## Data References`;for(let K of J.data){let Q=K.data.length>150?K.data.substring(0,147)+"...":K.data;B+=`
- ${Q}`}B+=`
`}if(J.intent?.length>0)B+=`
## Session Intent`,B+=`
${J.intent[J.intent.length-1].data}`,B+=`
`;if(J.role?.length>0)B+=`
## User Role`,B+=`
${J.role[J.role.length-1].data}`,B+=`
`;if(J.plan?.length>0){let K=J.plan.some((Z)=>Z.type==="plan_approved"),Q=J.plan.some((Z)=>Z.type==="plan_rejected"),X=J.plan.some((Z)=>Z.type==="plan_file_write"),U=J.plan[J.plan.length-1],Y=U.type==="plan_enter"||U.type==="plan_file_write";if(B+=`
## Plan Mode`,K)B+=`
- Status: APPROVED AND EXECUTED`,B+=`
- The plan was approved and executed. Do NOT re-enter plan mode or re-propose the same plan.`;else if(Q)B+=`
- Status: REJECTED BY USER`,B+=`
- The user rejected the previous plan. Ask what they want changed before re-planning.`;else if(Y){if(B+=`
- Status: ACTIVE (in planning phase)`,X)B+=`
- Plan file has been written. Awaiting user approval via ExitPlanMode.`}else B+=`
- Status: COMPLETED`,B+=`
- The plan has been executed. Do NOT re-enter plan mode or re-propose the same plan.`;B+=`
`}B+=`
</session_guide>`,B+=`
<session_search>`,B+=`
Detailed session data is indexed in context-mode FTS5 (source: "session-events").`;let $=H?H("ctx_search"):"ctx_search";if(B+=`
Use ${$}(queries: [...], source: "session-events") when you need specifics.`,B+=`
Do NOT call ctx_index() — data is already indexed.`,B+=`
</session_search>`,V&&L)B+=`
<continue_from>Continue working on the last request. Do NOT ask the user to repeat themselves.</continue_from>`;return B+=`
</session_knowledge>`,B}function D(G,_){return G.db.prepare(`SELECT session_id, type, category, priority, data, source_hook, created_at
     FROM session_events WHERE session_id = ? ORDER BY created_at ASC`).all(_)}function y(G){let _=G.db.prepare(`SELECT m.session_id FROM session_meta m
     JOIN session_events e ON m.session_id = e.session_id
     GROUP BY m.session_id
     ORDER BY m.started_at DESC LIMIT 1`).get();if(!_)return[];return D(G,_.session_id)}export{M as writeSessionEventsFile,w as groupEvents,D as getSessionEvents,y as getLatestSessionEvents,R as buildSessionDirective};
