Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   // ----------------------------------------------------------------------------
   // Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
   //
   // This library is free software; you can redistribute it and/or
   // modify it under the terms of the GNU Lesser General Public
   // License as published by the Free Software Foundation; either
   // version 2.1 of the License, or (at your option) any later version.
   //
   // This library is distributed in the hope that it will be useful,
  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  // Lesser General Public License for more details.
  //
  // You should have received a copy of the GNU Lesser General Public
  // License along with this library; if not, write to the Free Software
  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  //
  // To contact the authors:
  // http://www.inf.ufrgs.br/~bordini
  // http://www.das.ufsc.br/~jomi
  //
  //----------------------------------------------------------------------------
  
  package jason.asSemantics;
  
  
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  import java.util.Queue;
  
  
  public class TransitionSystem {
  
      public enum State { StartRC, SelEv, RelPl, ApplPl, SelAppl, FindOp, AddIM, ProcAct, SelInt, ExecInt, ClrInt }
      
      private Logger        logger     = null;
  
      private Agent         ag         = null;
      private AgArch        agArch     = null;
      private Circumstance  C          = null;
      private Settings      setts      = null;
      private State         step       = .// first step of the SOS                                                                                                
      private int           nrcslbr    = .// number of reasoning cycles since last belief revision    
      
      private boolean       sleepingEvt    = false;
      
      private List<GoalListener>  goalListeners = null;
      
      // both configuration and configuration' point to this
      // object, this is just to make it look more like the SOS
      private TransitionSystem      confP;
      private TransitionSystem      conf;
  
      
      public TransitionSystem(Agent aCircumstance cSettings sAgArch ar) {
               = a;
           = ar;
         
         if (s == null)
              = new Settings();
         else
              = s;
 
         if (c == null)
              = new Circumstance();
         else
              = c;
         .setTS(this);
         
         // we need to initialise this "aliases"
          =  = this;
 
          = .nrcbp(); // to do BR to start with
 
         setLogger();
         if ( != null && .verbose() >= 0)
             .setLevel(.logLevel());
         
         if (a != null)
             a.setTS(this);
         
         if (ar != null)
             ar.setTS(this);
     }
 
     public void setLogger(AgArch arch) {
         if (arch != null)
              = Logger.getLogger(TransitionSystem.class.getName() + "." + arch.getAgName());
         else
              = Logger.getLogger(TransitionSystem.class.getName());
     }
     public void setLogger(Logger l) {
          = l;
     }
     
     // ---------------------------------------------------------
     //    Goal Listeners support methods
     
     private Map<GoalListener,CircumstanceListenerlistenersMap// map the circumstance listeners created for the goal listeners, used in remove goal listener
     
    
adds an object that will be notified about events on goals (creation, suspension, ...)
 
     public void addGoalListener(final GoalListener gl) {
         if ( == null) {
              = new ArrayList<GoalListener>();
               = new HashMap<GoalListenerCircumstanceListener>();
         } else { 
             // do not install two MetaEventGoalListener
             for (GoalListener g)
                 if (g instanceof GoalListenerForMetaEvents)
                     return;
         }
         
         // we need to add a listener in C to map intention events to goal events
         CircumstanceListener cl = new CircumstanceListener() {
             
             public void intentionDropped(Intention i) {
                 for (IntendedMeans imi//.getIMs()) 
                     if (im.getTrigger().isAddition() && im.getTrigger().isGoal()) 
                         gl.goalFinished(im.getTrigger());                         
             }
             
             public void intentionSuspended(Intention iString reason) {
                 for (IntendedMeans imi//.getIMs()) 
                     if (im.getTrigger().isAddition() && im.getTrigger().isGoal()) 
                         gl.goalSuspended(im.getTrigger(), reason);                         
             }
             
             public void intentionResumed(Intention i) {
                 for (IntendedMeans imi//.getIMs()) 
                     if (im.getTrigger().isAddition() && im.getTrigger().isGoal()) 
                         gl.goalResumed(im.getTrigger());                         
             }
             
             public void eventAdded(Event e) {
                 if (e.getTrigger().isAddition() && e.getTrigger().isGoal())
                     gl.goalStarted(e);
             }
             
             public void intentionAdded(Intention i) {  }
         };
         .addEventListener(cl);
         .put(gl,cl);
 
         .add(gl);
     }
     
     public boolean hasGoalListener() {
         return  != null && !.isEmpty();
     }
     
     public List<GoalListenergetGoalListeners() {
         return ;
     }
     
     public boolean removeGoalListener(GoalListener gl) {
         CircumstanceListener cl = .get(gl);
         if (cl != null.removeEventListener(cl);
         return .remove(gl);
     }

    
 
     /* SEMANTIC RULES */
    
 
     
     private void applySemanticRule() throws JasonException {
         // check the current step in the reasoning cycle
         // only the main parts of the interpretation appear here
         // the individual semantic rules appear below
 
         switch () {
         case :   applyProcMsg(); break;
         case :     applySelEv(); break;
         case :     applyRelPl();  break;
         case :    applyApplPl(); break;
         case :   applySelAppl(); break;
         case :    applyFindOp(); break;
         case :     applyAddIM(); break;
         case :   applyProcAct(); break;
         case :    applySelInt(); break;
         case :   applyExecInt(); break;
         case :    . = .;
                         applyClrInt(..);
                         break;
         }
     }
 
     // the semantic rules are referred to in comments in the functions below
 
     private void applyProcMsg() throws JasonException {
         . = .;
         if (..hasMsg()) {
             Message m = ..selectMessage(..getMailBox());
             if (m == nullreturn;
             
             // get the content, it can be any term (literal, list, number, ...; see ask)
             Term content = null;
             if (m.getPropCont() instanceof Term) {
                 content = (Term)m.getPropCont();
             } else {
                 try {
                     content = ASSyntax.parseTerm(m.getPropCont().toString());
                 } catch (ParseException e) {
                     .warning("The content of the message '"+m.getPropCont()+"' is not a term!");
                     return;
                 }
             }
 
             // check if an intention was suspended waiting this message
             Intention intention = null;
             if (m.getInReplyTo() != null) {
                 intention = getC().getPendingIntentions().get(m.getInReplyTo());
             }
             // is it a pending intention?
             if (intention != null) {
                 // unify the message answer with the .send fourth argument.
                 // the send that put the intention in Pending state was
                 // something like
                 //    .send(ag1,askOne, value, X)
                 // if the answer was tell 3, unifies X=3
                 // if the answer was untell 3, unifies X=false
                 Structure send = (Structure)intention.peek().getCurrentStep().getBodyTerm();
                 if (m.isUnTell() && send.getTerm(1).toString().equals("askOne")) {
                     content = .;
                 } else if (content.isLiteral()) { // adds source in the content if possible
                     content = ((Literal)content).forceFullLiteralImpl();
                     ((Literal)content).addSource(new Atom(m.getSender()));
                 } else if (send.getTerm(1).toString().equals("askAll") && content.isList()) { // adds source in each answer if possible
                     ListTerm tail = new ListTermImpl();
                     for (Term t: ((ListTerm)content)) {
                         if (t.isLiteral()) {
                             t = ((Literal)t).forceFullLiteralImpl();
                             ((Literal)t).addSource(new Atom(m.getSender()));
                         }
                         tail.append(t);
                     }
                     content = tail;
                 }
                 
                 // test the case of sync ask with many receivers
                 Unifier un = intention.peek().getUnif();
                 Term rec = send.getTerm(0).capply(un);
                 if (rec.isList()) { // send to many receivers
                     // put the answers in the unifier
                     VarTerm answers = new VarTerm("AnsList___"+m.getInReplyTo());
                     ListTerm listOfAnswers = (ListTerm)un.get(answers);
                     if (listOfAnswers == null) {
                         listOfAnswers = new ListTermImpl();
                         un.unifies(answerslistOfAnswers);
                     }
                     listOfAnswers.append(content);
                     int nbReceivers = ((ListTerm)send.getTerm(0)).size();
                     if (listOfAnswers.size() == nbReceivers) { // all agents have answered
                         resumeSyncAskIntention(m.getInReplyTo(), send.getTerm(3), listOfAnswers);
                     }
                 } else {
                     resumeSyncAskIntention(m.getInReplyTo(), send.getTerm(3), content);
                 }
 
                 // the message is not an ask answer
             } else if (..socAcc(m)) {
 
                 if (! m.isReplyToSyncAsk()) { // ignore answer after the timeout
                     // generate an event
                     String sender = m.getSender();
                     if (sender.equals(getUserAgArch().getAgName()))
                         sender = "self";
                     
                     boolean added = false;
                     if (!.isSync() && !.getPL().hasUserKqmlReceivedPlans() && content.isLiteral() && !content.isList()) { // optimisation to jump kqmlPlans
                         if (m.getIlForce().equals("achieve") ) {                             
                             content = add_nested_source.addAnnotToList(contentnew Atom(sender));
                             .addEvent(new Event(new Trigger(.., (Literal)content), .));
                             added = true;                            
                         } else if (m.getIlForce().equals("tell") ) {
                             content = add_nested_source.addAnnotToList(contentnew Atom(sender));
                             getAg().addBel((Literal)content);
                             added = true;
                         }
                     }
                     
                     if (!added) {
                         Literal received = new LiteralImpl(.).addTerms(
                                 new Atom(sender),
                                 new Atom(m.getIlForce()),
                                 content,
                                 new Atom(m.getMsgId()));
                         
                         updateEvents(new Event(new Trigger(..received), .));
                     }
                 } else {
                     .fine("Ignoring message "+m+" because it is received after the timeout.");
                 }
             }
         }
     }
     
     private void resumeSyncAskIntention(String msgIdTerm answerVarTerm answerValuethrows JasonException {
         Intention i = getC().removePendingIntention(msgId);
         i.peek().removeCurrentStep(); // removes the .send in the plan body
         if (i.peek().getUnif().unifies(answerVaranswerValue)) {
             getC().resumeIntention(i);
         } else {
             generateGoalDeletion(i, JasonException.createBasicErrorAnnots("ask_failed""reply of an ask message ('"+answerValue+"') does not unify with fourth argument of .send ('"+answerVar+"')"));
         }                        
         
     }
 
     private void applySelEv() throws JasonException {
         
         // Rule for atomic, if there is an atomic intention, do not select event
         if (.hasAtomicIntention()) {
             . = .// need to go to ProcAct to see if an atomic intention received a feedback action
             return;            
         }
 
         // Rule for atomic, events from atomic intention have priority
         .. = .removeAtomicEvent();
         if (.. != null) {
             . = .;
             return;
         }
 
         if (..hasEvent()) {
             // Rule SelEv1
             .. = ..selectEvent(..getEvents());
             if (.isLoggable(.)) 
                 .fine("Selected event "+..);
             if (.. != null) {
                 if (.hasCustomSelectOption() || .verbose() == 2) // verbose == 2 means debug mode 
                     . = .;
                 else 
                     . = .;
                 return;
             }
         }
         // Rule SelEv2
         // directly to ProcAct if no event to handle
         . = .;
     }
 
     private void applyRelPl() throws JasonException {
         // get all relevant plans for the selected event
         .. = relevantPlans(...);
 
         // Rule Rel1
         if (.. != null || .retrieve()) 
             // retrieve is mainly for Coo-AgentSpeak
             . = .;
         else
             applyRelApplPlRule2("relevant");
     }
     
     private void applyApplPl() throws JasonException {
         .. = applicablePlans(..);
 
         // Rule Appl1
         if (.. != null || .retrieve()) 
             // retrieve is mainly for Coo-AgentSpeak
             . = .;
         else
             applyRelApplPlRule2("applicable");
     }

    
generates goal deletion event
 
     private void applyRelApplPlRule2(String mthrows JasonException {
         . = .// default next step
         if (....isGoal() && !....isMetaEvent()) {
             // can't carry on, no relevant/applicable plan.
             try {
                 if (...getIntention() != null && ...getIntention().size() > 3000) {
                     .warning("we are likely in a problem with event "+...getTrigger()+" the intention stack has already "+...getIntention().size()+" intended means!");                     
                 } 
                 String msg = "Found a goal for which there is no "+m+" plan:" + ...getTrigger();
                 if (!generateGoalDeletionFromEvent(JasonException.createBasicErrorAnnots("no_"+mmsg))) { 
                     .warning(msg);
                 }
             } catch (Exception e) {
                 e.printStackTrace();
                 return;
             }
                             
         } else if (...isInternal()) {
             // e.g. belief addition as internal event, just go ahead
             // but note that the event was relevant, yet it is possible
             // the programmer just wanted to add the belief and it was
             // relevant by chance, so just carry on instead of dropping the
             // intention
             .. = ...;
             updateIntention();
         } else if (.requeue()) {  
             // if external, then needs to check settings
             ..addEvent(..);
         } else {
             // current event is external and irrelevant,
             // discard that event and select another one
             . = .;
         }
     }
     
 
     private void applySelAppl() throws JasonException {
         // Rule SelAppl
         .. = ..selectOption(..);
 
         if (.. != null) {
             . = .;
             if (.isLoggable(.)) .fine("Selected option "+..+" for event "+..);
         } else {
             .fine("** selectOption returned null!");
             generateGoalDeletionFromEvent(JasonException.createBasicErrorAnnots("no_option""selectOption returned null"));
             // can't carry on, no applicable plan.
             . = .;
         }
     }

    
This step is new in Jason 1.1 and replaces the steps RelPl->ApplPl->SelAppl when the user does not customise selectOption. This version does not create the RP and AP lists and thus optimise the reasoning cycle. It searches for the first option and automatically selects it.

Since:
1.1
 
     private void applyFindOp() throws JasonException {
         . = .// default next step
         
         // get all relevant plans for the selected event
         //Trigger te = (Trigger) conf.C.SE.trigger.clone();
         List<PlancandidateRPs = ...getCandidatePlans(...);
         if (candidateRPs != null) {
             for (Plan pl : candidateRPs) {
                 Unifier relUn = pl.isRelevant(...);
                 if (relUn != null) { // is relevant
                     LogicalFormula context = pl.getContext();
                     if (context == null) { // context is true
                         .. = new Option(plrelUn);
                         return;
                     } else {
                         Iterator<Unifierr = context.logicalConsequence(relUn);
                         if (r != null && r.hasNext()) {
                             .. = new Option(plr.next());
                             return;
                         }
                     } 
                 }
             }
             applyRelApplPlRule2("applicable");   
         } else {
             // problem: no plan
             applyRelApplPlRule2("relevant");   
         }        
     }
     
     private void applyAddIM() throws JasonException {
         // create a new intended means
         IntendedMeans im = new IntendedMeans(.....getTrigger());
 
         // Rule ExtEv
         if (... == .) {
             Intention intention = new Intention();
             intention.push(im);
             ..addIntention(intention);
         } else {
             // Rule IntEv
             
             // begin tail recursion optimisation (TRO)
             if (.isTROon()) {
                 IntendedMeans top = ....peek(); // top = the IM that will be removed from the intention due to TRO
                 if (top != null && top.getTrigger().isGoal() && im.getTrigger().isGoal() && // are both goal
                         top.getCurrentStep().getBodyNext() == null && // the plan below is finished
                         top.getTrigger().getPredicateIndicator().equalsim.getTrigger().getPredicateIndicator()) // goals are equals
                     ) { 
                     ....pop(); // remove the top IM
                     
                     IntendedMeans imBase = ....peek(); // base = where the new IM will be place on top of
                     if (imBase != null) {
                         // move top relevant values into the base (relevant = renamed vars in base)
                         for (VarTerm vimBase.renamedVars) {
                             VarTerm vvl = (VarTerm)imBase.renamedVars.function.get(v);
                             Term t = top.unif.get(vvl);
                             if (t != null) { // if v has got a value in top unif, put the value in the unifier
                                 if (t instanceof Literal) {
                                     //Literal l= (Literal)t.clone();
                                     //l.apply(top.unif);
                                     Literal l= (Literal)t.capply(top.unif);
                                     l.makeVarsAnnon(top.renamedVars);
                                     im.unif.function.put(vvll);                        
                                 } else {
                                     im.unif.function.put(vvlt);                        
                                 }
                             } else {
                                 // the vvl was renamed again in top, just replace in base the new value
                                 VarTerm v0 = (VarTerm)top.renamedVars.function.get(vvl);
                                 if (v0 != null) {
                                     imBase.renamedVars.function.put(vv0);
                                 }
                             }
                         }            
                     }
                 }           
                 // end of TRO
             }
 
             ....push(im);
             ..addIntention(...);
         }
         . = .;
     }
 
     private void applyProcAct() throws JasonException {
         . = .// default next step
         if (..hasFeedbackAction()) {
             ActionExec a = null;
             synchronized (..getFeedbackActions()) {
                 a = ..selectAction(..getFeedbackActions());
             }
             if (a != null) {
                 .. = a.getIntention();
 
                 // remove the intention from PA (PA has all pending action, including those in FA;
                 // but, if the intention is not in PA, it means that the intention was dropped
                 // and should not return to I)
                 if (.removePendingAction(...getId()) != null) {
                     if (a.getResult()) {
                         // add the intention back in I
                         updateIntention();
                         applyClrInt(..);
                         
                         if (hasGoalListener())
                             for (GoalListener glgetGoalListeners())
                                 for (IntendedMeans im..//.getIMs())
                                     gl.goalResumed(im.getTrigger());
                     } else {
                         String reason = a.getFailureMsg();
                         if (reason == nullreason = "";
                         ListTerm annots = JasonException.createBasicErrorAnnots("action_failed"reason);
                         if (a.getFailureReason() != null
                             annots.append(a.getFailureReason());
                         generateGoalDeletion(..annots);
                         .removeAtomicIntention(); // if (potential) atomic intention is not removed, it will be selected in selInt or selEv and runs again
                     }
                 } else {
                     applyProcAct(); // get next action
                 }
             }
         }
     }
 
     private void applySelInt() throws JasonException {
         . = .// default next step
 
         // Rule for Atomic Intentions
         .. = .removeAtomicIntention();
         if (.. != null) {
             return;
         }
         
         // Rule SelInt1
         if (!..isAtomicIntentionSuspended() && ..hasIntention()) { // the isAtomicIntentionSuspended is necessary because the atomic intention may be suspended (the above removeAtomicInt returns null in that case)
                                                                              // but no other intention could be selected
             .. = ..selectIntention(..getIntentions());
             if (.isLoggable(.)) .fine("Selected intention "+..);            
             if (.. != null) { // the selectIntention function returned null
                 return;             
             }
         }
 
         . = .;
     }
 
     @SuppressWarnings("unchecked")
     private void applyExecInt() throws JasonException {
         . = .// default next step
         
         if (...isFinished()) {
             return;
         }
         
         // get next formula in the body of the intended means
         // on the top of the selected intention
 
         IntendedMeans im = ...peek();
 
         if (im.isFinished()) { 
             // for empty plans! may need unif, etc
             updateIntention();
             return;
         }
         Unifier     u = im.unif;
         PlanBody    h = im.getCurrentStep();
         
         Term bTerm = h.getBodyTerm();
 
         if (bTerm instanceof VarTerm) { // de-var bTerm
             bTerm = bTerm.capply(u);
             if (bTerm.isVar()) { // the case of !A with A not ground
                 String msg = h.getSrcInfo()+": ""Variable '"+bTerm+"' must be ground.";
                 if (!generateGoalDeletion(.., JasonException.createBasicErrorAnnots("body_var_without_value"msg)))
                     .log(.msg);
                 return;
             }
             if (bTerm.isPlanBody()) { 
                 if (h.getBodyType() != .) { // the case of ...; A = { !g }; +g; ....
                     String msg = h.getSrcInfo()+": ""The operator '"+h.getBodyType()+"' is lost with the variable '"+bTerm+"' unified with a plan body. ";
                     if (!generateGoalDeletion(.., JasonException.createBasicErrorAnnots("body_var_with_op"msg))) 
                         .log(.msg);
                     return;
                 }
                 h = (PlanBody)bTerm;
                 if (h.getPlanSize() > 1) { // the case of A unified with {a;b;c}
                     h.add(im.getCurrentStep().getBodyNext());
                     im.insertAsNextStep(h.getBodyNext());
                 }
                 bTerm = h.getBodyTerm();
             }
         }
             
         Literal body = null;
         if (bTerm instanceof Literal)
             body = (Literal)bTerm;
 
         switch (h.getBodyType()) {
 
         case break;
         
         // Rule Action
         case :
             body = (Literal)body.capply(u);
             .. = new ActionExec(body..);
             break;
 
         case :
             boolean ok = false;
             List<TermerrorAnnots = null;
             try {
                 InternalAction ia = ((InternalActionLiteral)bTerm).getIA();
                 Term[] terms      = ia.prepareArguments(bodyu); // clone and apply args
                 Object oresult    = ia.execute(thisuterms);
                 if (oresult != null) {
                     ok = oresult instanceof Boolean && (Boolean)oresult;
                     if (!ok && oresult instanceof Iterator) { // ia result is an Iterator
                         Iterator<Unifieriu = (Iterator<Unifier>)oresult;
                         if (iu.hasNext()) {
                             // change the unifier of the current IM to the first returned by the IA
                             im.unif = iu.next(); 
                             ok = true;
                         }
                     }
                     if (!ok) { // IA returned false
                         errorAnnots = JasonException.createBasicErrorAnnots("ia_failed"""); 
                     }
                 }
 
                 if (ok && !ia.suspendIntention())
                     updateIntention();
             } catch (JasonException e) {
                 errorAnnots = e.getErrorTerms();
                 if (!generateGoalDeletion(..errorAnnots))
                     .log(.body.getErrorMsg()+": "e.getMessage());
                 ok = true// just to not generate the event again
             } catch (Exception e) {
                 if (body == null
                     .log(."Selected an intention with null body in '"+h+"' and IM "+ime);
                 else
                     .log(.body.getErrorMsg()+": "e.getMessage(), e);
             }
             if (!ok)
                 generateGoalDeletion(..errorAnnots);
 
             break;
 
         case :
             Iterator<Unifieriu = ((LogicalFormula)bTerm).logicalConsequence(u);
             if (iu.hasNext()) {
                 im.unif = iu.next();
                 updateIntention();
             } else {
                 String msg = "Constraint "+h+" was not satisfied ("+h.getSrcInfo()+") un="+u;
                 generateGoalDeletion(.., JasonException.createBasicErrorAnnots(new Atom("constraint_failed"), msg));
                 .fine(msg);
             }
             break;
 
         // Rule Achieve
         case :
             body = prepareBodyForEvent(bodyu...peek());
             Event evt = ..addAchvGoal(body..);
             . = .;
             checkHardDeadline(evt);
             break;
 
         // Rule Achieve as a New Focus (the !! operator)
         case :
             body = prepareBodyForEvent(bodyunull);
             evt  = ..addAchvGoal(body.);
             checkHardDeadline(evt);
             updateIntention();
             break;
 
         // Rule Test
         case :
             LogicalFormula f = (LogicalFormula)bTerm;
             if (..believes(fu)) {
                 updateIntention();
             } else {
                 boolean fail = true;
                 // generate event when using literal in the test (no events for log. expr. like ?(a & b))
                 if (f.isLiteral() && !(f instanceof BinaryStructure)) { 
                     body = prepareBodyForEvent(bodyu...peek());
                     if (body.isLiteral()) { // in case body is a var with content that is not a literal (note the VarTerm pass in the instanceof Literal)
                         Trigger te = new Trigger(..body);
                         evt = new Event(te..);
                         if (.getPL().hasCandidatePlan(te)) {
                             if (.isLoggable(.)) .fine("Test Goal '" + h + "' failed as simple query. Generating internal event for it: "+te);
                             ..addEvent(evt);
                             . = .;
                             fail = false;
                         }
                     }
                 }
                 if (fail) {
                     if (.isLoggable(.)) .fine("Test '"+h+"' failed ("+h.getSrcInfo()+").");
                     generateGoalDeletion(.., JasonException.createBasicErrorAnnots("test_goal_failed""Failed to test '"+h+"'"));
                 }
             }
             break;
 
             
         case 
             // -+a(1,X) ===> remove a(_,_), add a(1,X)
             // change all vars to anon vars to remove it
             Literal b2 = prepareBodyForEvent(bodyu...peek()); 
             b2.makeTermsAnnon(); // do not change body (but b2), to not interfere in addBel
             // to delete, create events as external to avoid that
             // remove/add create two events for the same intention
             // (in future releases, creates a two branches for this operator)
 
             try {
                 List<Literal>[] result = .brf(nullb2..); // the intention is not the new focus
                 if (result != null) { // really delete something
                     // generate events
                     updateEvents(result,.);
                 }
             } catch (RevisionFailedException re) {
                 generateGoalDeletion(.., JasonException.createBasicErrorAnnots("belief_revision_failed""BRF failed for '"+body+"'"));
                 break;
             }
 
             // add the belief, so no break;
             
         // Rule AddBel
         case :
         case :
         case :
         case :
             // calculate focus
             Intention newfocus = .;
             boolean isSameFocus = .sameFocus() && h.getBodyType() != .;
             if (isSameFocus) {
                 newfocus = ..;
                 body = prepareBodyForEvent(bodyunewfocus.peek());
             } else {
                 body = prepareBodyForEvent(bodyunull);
             }
             
             // call BRF
             try {
                 List<Literal>[] result;
                 if (h.getBodyType() == .)
                     result = .brf(body,null,..true); 
                 else
                     result = .brf(body,null,..); // use default (well documented and used) method in case someone has overridden it 
                 if (result != null) { // really added something
                     // generate events
                     updateEvents(result,newfocus);
                     if (!isSameFocus) {
                         updateIntention();
                     }                    
                 } else {
                     updateIntention();                    
                 }
             } catch (RevisionFailedException re) {
                 generateGoalDeletion(..null);
             }
             break;
             
         case :
 
             newfocus = .;
             if (.sameFocus()) {
                 newfocus = ..;
                 body = prepareBodyForEvent(bodyunewfocus.peek());
             } else {
                 body = prepareBodyForEvent(bodyunull);
             }
             // call BRF
             try {
                 List<Literal>[] result = .brf(nullbody..); // the intention is not the new focus
                 if (result != null) { // really change something
                     // generate events
                     updateEvents(result,newfocus);
                     if (!.sameFocus()) {
                         updateIntention();
                     }                    
                 } else {
                     updateIntention();                    
                 }
             } catch (RevisionFailedException re) {
                 generateGoalDeletion(..null);
             }            
             break;
         }
     }
     
     // add the self source in the body in case no other source was given
     private Literal prepareBodyForEvent(Literal bodyUnifier uIntendedMeans imRenamedVars) {
         body = (Literal)body.capply(u);
         Unifier renamedVars = new Unifier();
         //System.out.println("antes "+body+" "+u+" ");
         body.makeVarsAnnon(renamedVars); // free variables in an event cannot conflict with those in the plan
         if (imRenamedVars != null) {
             imRenamedVars.renamedVars = renamedVars;
             
             // Code for TRO (Tail Recursion Opt)
             if (.isTROon()) {
                 // renamed vars binded with another var in u need to be preserved (since u will be lost in TRO)
                 Map<VarTermTermadds = null;
                 for (VarTerm vrenamedVars) {
                     Term t = u.function.get(v);
                     if (t != null) {
                         //System.out.println("adding "+t+"="+renamedVars.function.get(v));
                         if (adds == null)
                             adds = new HashMap<VarTermTerm>();
                         try {
                             adds.put((VarTerm)t,renamedVars.function.get(v));                            
                         } catch (Exception e) {
                             .log(."*** Error adding var into renamed vars. var="+v+", value="+t+"."e);
                         }
                     }
                 }
                 if (adds != null)
                     renamedVars.function.putAll(adds);
                 // end code for TRO
             }
         }
 
         body = body.forceFullLiteralImpl();
         if (!body.hasSource()) { // do not add source(self) in case the programmer set the source
             body.addAnnot(.);
         }
         return body;
     }
 
     public void applyClrInt(Intention ithrows JasonException {
         while (true) { // quit the method by return
             // Rule ClrInt
             if (i == null)
                 return;
             
             if (i.isFinished()) {
                 // intention finished, remove it
                 ..dropIntention(i);
                 //conf.C.SI = null;
                 return;
             }
     
             IntendedMeans im = i.peek();
             if (!im.isFinished()) {
                 // nothing to do
                 return;
             }
     
             // remove the finished IM from the top of the intention
             IntendedMeans topIM = i.pop();
             Trigger topTrigger = topIM.getTrigger();
             Literal topLiteral = topTrigger.getLiteral();
             if (.isLoggable(.)) .fine("Returning from IM "+topIM.getPlan().getLabel()+", te="+topIM.getPlan().getTrigger()+" unif="+topIM.unif);
             
             // produce ^!g[state(finished)] event
             if (topTrigger.getOperator() == . && topTrigger.isGoal()) {
                 if (hasGoalListener())
                     for (GoalListener gl)
                         gl.goalFinished(topTrigger);
             }
             
             // if has finished a failure handling IM ...
             if (im.getTrigger().isGoal() && !im.getTrigger().isAddition() && !i.isFinished()) {//i.size() > 0) {
                 // needs to get rid of the IM until a goal that
                 // has failure handling. E.g,