code: func desiredAgentState(a *Agent, reg registry.Registry) (*AgentState, error) {
  	units, err := reg.Units()
  	if err != nil {
  		log.Errorf("Failed fetching Units from Registry: %v", err)
  		return nil, err
  	}
  
  	sUnits, err := reg.Schedule()
  	if err != nil {
  		log.Errorf("Failed fetching schedule from Registry: %v", err)
  		return nil, err
  	}
  
  	// fetch full machine state from registry instead of
  	// using the local version to allow for dynamic metadata
  	ms, err := reg.MachineState(a.Machine.State().ID)
  	if err != nil {
  		log.Errorf("Failed fetching machine state from Registry: %v", err)
  		return nil, err
  	}
  	as := AgentState{
  		MState: &ms,
  		Units:  make(map[string]*job.Unit),
  	}
  
  	sUnitMap := make(map[string]*job.ScheduledUnit)
  	for _, sUnit := range sUnits {
  		sUnit := sUnit
  		sUnitMap[sUnit.Name] = &sUnit
  	}
  
  	for _, u := range units {
  		u := u
  		md := u.RequiredTargetMetadata()
  
  		if u.IsGlobal() {
  			if !machine.HasMetadata(&ms, md) {
  				log.Debugf("Agent unable to run global unit %s: missing required metadata", u.Name)
  				continue
  			}
  		}
  
  		if !u.IsGlobal() {
  			sUnit, ok := sUnitMap[u.Name]
  			if !ok || sUnit.TargetMachineID == "" || sUnit.TargetMachineID != ms.ID {
  				continue
  			}
  		}
  
  		if cExists, _ := as.HasConflict(u.Name, u.Conflicts()); cExists {
  			continue
  		}
  
  		as.Units[u.Name] = &u
  	}
  
  	return &as, nil
  }
docs: // desiredAgentState builds an *AgentState object that represents what the
  // provided Agent should currently be doing.