Why this matters
If you only learn one runtime subsystem, learn this one. The query layer is the heart of how Claude Code thinks, streams, stops, and recovers.
Big picture first
The query subsystem takes prepared messages, runs the model loop, reacts to tool calls, and decides whether the session should continue, compact, or stop.
One turn through the query engine
- Start with prepared messages, config, and tool context.
- Enter the main loop in query.ts.
- Stream assistant output and detect tool uses.
- Run tools, stop hooks, or recovery paths when needed.
- Return a terminal state for the turn.
How this part breaks down
query-loop-and-state-machineThis is the main runtime loop and the mutable state it carries.query-prompts-and-recovery-messagesThis is the direct text the system injects when it needs special behavior.query-budget-and-stop-hooksThis is where the runtime decides whether to continue or switch into post-turn work.query-tool-orchestrationThis is how tool calls become actual execution.query-compaction-and-recoveryThis is how the runtime shrinks history and survives prompt-too-long situations.
Takeaways
- The query root is a parent chapter, not a file-by-file deep dive.
- Each child page follows the same top-down teaching rhythm.
- You should understand the loop before you study edge recovery paths.