Goal Stacks and Backtracking
Push sub-goals onto a stack, pop on completion, backtrack on dead ends — classic AI planning.
Goal Stacks and Backtracking is a free AI Agents lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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
# --- demo ---
push('write the report')
push('collect the data')
print(f'Current goal: {current()}')
print(f'Popped: {pop()}')
print(f'Current goal after pop: {current()}')
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()Backtracking
When a goal fails:
- Mark it failed
- Pop back to the parent
- Try a different approach (different sub-goals)
Backtracking Example
def attempt(goal):
for approach in [oauth, saml, custom_token]:
try:
return run_with(goal, approach)
except FailedException:
continue
raise NoApproachWorked(goal)Tracking Tried Approaches
Avoid retrying the same failed approach. Track what was tried per goal:
{
'goal_id': 'refactor-auth',
'tried': ['oauth', 'saml'],
'remaining_options': ['custom_token']
}LLM as Goal Picker
Use the LLM to decide what to push next:
next_goal = llm.invoke(f'Current goal: {current()}. Done so far: {done_list}. What sub-goal next?').content
push(next_goal)Pre-Conditions and Effects
Borrow from STRIPS planning: each action has preconditions (what must be true) and effects (what becomes true):
action = {
'name': 'replace_login',
'preconditions': ['oauth_dep_installed'],
'effects': ['login_endpoint_replaced']
}Planning vs Acting Loop
Two-phase approach:
- Plan — symbolic planner builds the goal stack
- Act — agent executes top of stack, updates world state, replans if needed
Hybrid Symbolic + LLM
For tasks with clean preconditions (file ops, deployments), use a symbolic planner. For fuzzy parts, use the LLM. Combine for robustness.
Dead-Ends
Sometimes the agent reaches a state where no action helps. Recognize dead-ends and backtrack further:
if no_progress_in_n_steps(5):
pop_to_parent()
try_different_approach()Limit Backtracking Depth
Unbounded backtracking can loop forever. Cap depth and total iterations:
MAX_BACKTRACKS = 10
if backtrack_count >= MAX_BACKTRACKS:
escalate_to_human()Surface Backtracks to Users
When the agent backtracks, tell the user: "OAuth didn't work, trying SAML." Maintains trust and lets them intervene early.
Backtracking Trigger
When should the agent backtrack from a sub-goal?
Recap
Goal stack tracks the agent's "where am I?". Push sub-goals, pop completed ones, backtrack on dead ends. Combine symbolic planning with LLM judgment.
Frequently asked questions
Is the “Goal Stacks and Backtracking” lesson free?
Yes — the full text of “Goal Stacks and Backtracking” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Goal Stacks and Backtracking”?
Push sub-goals onto a stack, pop on completion, backtrack on dead ends — classic AI planning. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Goal Stacks and Backtracking” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Hierarchical Task Decomposition
- Goal Stacks and Backtracking
- World Models and Lookahead
- Reflection and Self-Critique Loops