0PricingLogin
AI Agents · Lesson

Goal Stacks and Backtracking

Push sub-goals onto a stack, pop on completion, backtrack on dead ends — classic AI planning.

A Stack of Goals

Classical AI planning uses a goal stack: push sub-goals as you encounter them, pop when complete. Agents can use the same data structure:

goal_stack = []

def push(goal):
    goal_stack.append(goal)

def pop():
    return goal_stack.pop() if goal_stack else None

def current():
    return goal_stack[-1] if goal_stack else None

Example: Refactoring Workflow

push('Refactor auth')
while current():
    g = current()
    if g == 'Refactor auth':
        if not done('add_oauth_dep'):
            push('Add OAuth dependency')
        elif not done('replace_login'):
            push('Replace login endpoint')
        else:
            pop()   # done
    elif g == 'Add OAuth dependency':
        # ...actually do the work...
        mark_done('add_oauth_dep')
        pop()

All lessons in this course

  1. Hierarchical Task Decomposition
  2. Goal Stacks and Backtracking
  3. World Models and Lookahead
  4. Reflection and Self-Critique Loops
← Back to AI Agents