#!/usr/bin/env node
import{createRequire as E}from"node:module";var U=E(import.meta.url);import"./suppress-stderr.mjs";import"./ensure-deps.mjs";import{createRoutingBlock as R}from"./routing-block.mjs";import{createToolNamer as y}from"./core/tool-naming.mjs";import{readStdin as B,getSessionId as O,getSessionDBPath as _,getSessionEventsPath as x,getCleanupFlagPath as j}from"./session-helpers.mjs";import{writeSessionEventsFile as k,buildSessionDirective as C,getSessionEvents as D,getLatestSessionEvents as v}from"./session-directive.mjs";import{createSessionLoaders as P}from"./session-loaders.mjs";import{join as $,dirname as m}from"node:path";import{fileURLToPath as b}from"node:url";import{readFileSync as p,unlinkSync as F,readdirSync as g,rmSync as u,statSync as h}from"node:fs";import{homedir as S}from"node:os";var w=y(),I=R(w),l=m(b(import.meta.url)),{loadSessionDB:T}=P(l),L=I;try{let V=await B(),W=JSON.parse(V),X=W.source??"startup";if(X==="compact"){let{SessionDB:Q}=await T(),Y=_(),q=new Q({dbPath:Y}),z=O(W),A=q.getResume(z);if(A&&!A.consumed)q.markResumeConsumed(z);let G=D(q,z);if(G.length>0){let J=k(G,x());L+=C("compact",J,w)}q.close()}else if(X==="resume"){try{F(j())}catch{}let{SessionDB:Q}=await T(),Y=_(),q=new Q({dbPath:Y}),z=v(q);if(z.length>0){let A=k(z,x());L+=C("resume",A,w)}q.close()}else if(X==="startup"){let{SessionDB:Q}=await T(),Y=_(),q=new Q({dbPath:Y});try{F(x())}catch{}q.cleanupOldSessions(7),q.db.exec("DELETE FROM session_events WHERE session_id NOT IN (SELECT session_id FROM session_meta)");let z=O(W),A=process.env.PUKU_PROJECT_DIR||process.cwd();q.ensureSession(z,A);let G=[$(S(),".claude","CLAUDE.md"),$(A,"CLAUDE.md"),$(A,".claude","CLAUDE.md")];for(let J of G)try{let Z=p(J,"utf-8");if(Z.trim())q.insertEvent(z,{type:"rule",category:"rule",data:J,priority:1}),q.insertEvent(z,{type:"rule_content",category:"rule",data:Z,priority:1})}catch{}q.close();try{let J=process.env.PUKU_PLUGIN_ROOT;if(J){let Z=J.match(/^(.*[\\/]plugins[\\/]cache[\\/][^\\/]+[\\/][^\\/]+[\\/])/);if(Z){let H=Z[1],M=J.replace(H,"").replace(/[\\/]/g,""),c=3600000,N=Date.now();for(let K of g(H)){if(K===M)continue;try{let f=h($(H,K));if(N-f.mtimeMs>3600000)u($(H,K),{recursive:!0,force:!0})}catch{}}}}}catch{}}}catch(V){try{let{appendFileSync:W}=await import("node:fs"),{join:X}=await import("node:path"),{homedir:Q}=await import("node:os");W(X(Q(),".puku-cli","context-mode","sessionstart-debug.log"),`[${new Date().toISOString()}] ${V?.message||V}
${V?.stack||""}
`)}catch{}}console.log(JSON.stringify({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:L}}));
