import{basename,dirname,join,resolve}from"node:path";import{DISCOVER_PROJECT_NOT_FOUND,createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{classifyAgentRootEntry,getDirectoryEntryType,isProjectMarkerEntry}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";var DiscoveryProjectResolutionError=class extends Error{diagnostic;constructor(e){super(e.message),this.name=`DiscoveryProjectResolutionError`,this.diagnostic=e}};async function resolveDiscoveryProject(e=process.cwd(),n={}){let r=n.source??createDiskProjectSource(),a=await resolveSearchDirectory(r,e),o=a;for(;;){let e=await tryResolveNestedProjectFromAgentDirectory(r,o);if(e!==null)return e;let n=await tryResolveNestedProjectFromAppRoot(r,o);if(n!==null)return n;if(await isFlatAgentRoot(r,o))return{agentRoot:o,appRoot:o,layout:`flat`};let i=dirname(o);if(i===o)break;o=i}throw new DiscoveryProjectResolutionError(createDiscoverErrorDiagnostic({code:DISCOVER_PROJECT_NOT_FOUND,message:`Could not resolve an Eve agent root from "${a}".`,sourcePath:a}))}async function resolveSearchDirectory(e,n){let i=resolve(n);return await e.stat(i)===`directory`?i:dirname(i)}async function tryResolveNestedProjectFromAgentDirectory(n,r){if(basename(r)!==`agent`)return null;let i=dirname(r);return await hasProjectMarkers(n,i)?{agentRoot:r,appRoot:i,layout:`nested`}:null}async function tryResolveNestedProjectFromAppRoot(e,t){if(!await hasProjectMarkers(e,t))return null;let r=join(t,`agent`);return await directoryExists(e,r)?{agentRoot:r,appRoot:t,layout:`nested`}:null}async function isFlatAgentRoot(e,t){let n=await readDirectoryEntryTypes(e,t);return Array.from(n.entries()).some(([e,t])=>{let n=classifyAgentRootEntry(e,t);return n!==`unknown`&&n!==`lib-directory`})}async function hasProjectMarkers(e,t){let n=await readDirectoryEntryTypes(e,t);return Array.from(n.entries()).some(([e,t])=>isProjectMarkerEntry(e,t))}async function readDirectoryEntryTypes(e,t){if(await e.stat(t)!==`directory`)return new Map;let n=await e.readDirectory(t);return new Map(n.map(e=>[e.name,getDirectoryEntryType(e)]))}async function directoryExists(e,t){return await e.stat(t)===`directory`}export{DiscoveryProjectResolutionError,resolveDiscoveryProject};