Build an AI Agent Flight Recorder

Trace and debug a simulated support agent with a local timeline and tests.

Introduction

30 Second Summary

A support agent can return a polished answer while hiding every decision that produced it. When that workflow fails, a generic error leaves you guessing where the run broke.

In this project, you will turn a simulated support agent into a traceable workflow with a local flight recorder. You will use correlated JSONL traces to diagnose a routing failure before proving the repair with deterministic tests.

What You'll Build

Your browser timeline will let you open any agent run to pinpoint its route decision, nested operations, timing, and first failed span.

By the end of this project, you'll have:

  • A set of deterministic agent scenarios that reproduce normal runs, routing failures, timeouts, malformed responses, and intermittent-looking failures locally.
  • A local trace timeline powered by FastAPI. You can follow each operation under one trace ID and see exactly where an error started.
  • An observability scorecard that reports trace completeness, failure attribution, span integrity, recovery success, and separate latency measurements. A pytest suite proves those guarantees remain intact.
  • Secret Mission: recover an every-third-run timeout with one bounded retry while preserving the failed attempt as trace evidence.

Are there any prerequisites?

You need the provided starter repository plus Python 3.11 or newer. You also need VS Code and Git.

No API key, cloud account, Docker runtime, or external LLM is required.

Before We Start

A support agent can hide the operation that failed. It can also hide the route decision, timing, or error behind that failure. This project commits you to using correlated execution evidence instead of guessing from source code.

Verify and Launch the Starter Agent

Create and Launch the Starter Agent

You will build the starter project directly in VS Code. Creating the files yourself removes every dependency on a ZIP, repository, or workshop download.

The baseline uses Python 3.11 or newer. You will create every required file before running the first command.

In this step, get ready to:
  • Create the complete project in a new VS Code workspace.
  • Set up an isolated Python environment with pinned dependencies.
  • Run the healthy password reset scenario.
Create the workspace and files
  • Press Cmd+Space on macOS, the Windows key on Windows, or open application search on Linux.
  • Type Visual Studio Code and press Enter.
  • Click File in the top menu.
  • Click Open Folder.
  • Open your Desktop in the folder picker.
  • Create a new folder named ai-agent-flight-recorder.
  • Select the new folder and click Open.
  • Confirm that you trust the folder if VS Code displays a workspace trust prompt.

The empty ai-agent-flight-recorder folder should now be the only top-level folder in the Explorer sidebar.

  • Click the Explorer icon in the left sidebar.
  • Click the New File icon beside the folder name.
  • Enter flight_recorder.py and press Enter.
  • Repeat the New File action for retry_policy.py, viewer.py, requirements.txt, .gitignore, and README.md.

How to paste the numbered chunks

Open flight_recorder.py. Paste Chunks 1 through 7 consecutively in the same file, with each new chunk directly below the previous chunk.

Do not replace an earlier chunk when you paste the next one. The full-file tab after Chunk 7 is an exact comparison copy of the assembled file.

  • Paste Chunk 1 into the empty flight_recorder.py file:
import argparse
import json
import logging
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from secrets import token_hex
from time import perf_counter

from retry_policy import should_retry

TRACE_PATH = Path("traces/agent.jsonl")
RECOVERY_SCENARIOS = ["password_reset", "shipping_delay", "warranty_question", "refund_route"]
SCENARIOS = {
    "password_reset": {"category": "password", "expected_tool": "knowledge_search", "latency": [4, 8, 18, 5]},
    "shipping_delay": {"category": "shipping", "expected_tool": "order_lookup", "latency": [4, 7, 24, 5]},
    "warranty_question": {"category": "warranty", "expected_tool": "knowledge_search", "latency": [3, 9, 16, 6]},
    "refund_route": {"category": "refund", "expected_tool": "billing_lookup", "latency": [4, 8, 20, 5]},
    "timeout_probe": {"category": "password", "expected_tool": "knowledge_search", "latency": [4, 8, 50, 0], "failure": "timeout"},
    "malformed_probe": {"category": "warranty", "expected_tool": "knowledge_search", "latency": [3, 9, 15, 0], "failure": "malformed"},
    "flaky_timeout": {"category": "password", "expected_tool": "knowledge_search", "latency": [3, 6, 30, 4], "failure": "every_third_timeout"},
}
  • Paste Chunk 2 directly below Chunk 1:

class AgentFailure(RuntimeError):
    pass


class IncorrectRoute(AgentFailure):
    pass


class ToolTimeout(AgentFailure):
    pass


class MalformedToolResponse(AgentFailure):
    pass


def utc_now():
    return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")


class JsonlFormatter(logging.Formatter):
    def format(self, record):
        # Step 3 replaces this placeholder with JSON serialization.
        return record.getMessage()


class FlightRecorder:
    def __init__(self, path=TRACE_PATH):
        self.path = Path(path)
        self.path.parent.mkdir(parents=True, exist_ok=True)
  • Paste Chunk 3 directly below Chunk 2:
        self.logger = logging.getLogger(f"flight-recorder.{token_hex(4)}")
        self.logger.setLevel(logging.INFO)
        self.logger.propagate = False
        self.handler = logging.FileHandler(self.path, encoding="utf-8")
        self.handler.setFormatter(JsonlFormatter())
        self.logger.addHandler(self.handler)

    def new_trace(self):
        return token_hex(16)

    @contextmanager
    def span(self, operation, trace_id, parent_span_id=None, attributes=None):
        # Step 3 turns this placeholder into a completed JSONL span.
        yield {"span_id": token_hex(8), "attributes": dict(attributes or {}), "simulated_latency_ms": 0}

    def close(self):
        self.logger.removeHandler(self.handler)
        self.handler.close()


class NullRecorder:
    def new_trace(self):
        return token_hex(16)

    @contextmanager
    def span(self, operation, trace_id, parent_span_id=None, attributes=None):
        yield {"span_id": token_hex(8), "attributes": dict(attributes or {}), "simulated_latency_ms": 0}
  • Paste Chunk 4 directly below Chunk 3:

def select_tool(category, repaired):
    buggy_routes = {"password": "knowledge_search", "shipping": "order_lookup", "warranty": "knowledge_search", "refund": "knowledge_search"}
    repaired_routes = {**buggy_routes, "refund": "billing_lookup"}
    return (repaired_routes if repaired else buggy_routes)[category]


def retrieve_context(scenario_name):
    return f"support context for {scenario_name}"


def call_tool(scenario_name, selected_tool, run_number, attempt):
    scenario = SCENARIOS[scenario_name]
    if selected_tool != scenario["expected_tool"]:
        raise IncorrectRoute(f"expected {scenario['expected_tool']}, got {selected_tool}")
    failure = scenario.get("failure")
    if failure == "timeout":
        raise ToolTimeout("simulated tool deadline exceeded")
    if failure == "malformed":
        raise MalformedToolResponse("simulated response has no recommendation")
    if failure == "every_third_timeout" and run_number % 3 == 0 and attempt == 1:
        raise ToolTimeout("simulated every-third-run timeout")
    return {"recommendation": f"Use {selected_tool} evidence for {scenario_name}."}


def run_agent(scenario_name, recorder, repaired=False, run_number=1):
    scenario = SCENARIOS[scenario_name]
    trace_id = recorder.new_trace()
    started = perf_counter()
  • Paste Chunk 5 directly below Chunk 4. Its indentation continues the existing try block:
    simulated_total = 0
    try:
        selected_tool = select_tool(scenario["category"], repaired)
        context = retrieve_context(scenario_name)
        simulated_total += scenario["latency"][0] + scenario["latency"][1]
        attempt = 1
        while True:
            try:
                tool_result = call_tool(scenario_name, selected_tool, run_number, attempt)
                simulated_total += scenario["latency"][2]
                break
            except AgentFailure as exc:
                if should_retry(type(exc).__name__, attempt, selected_tool):
                    attempt += 1
                    continue
                raise
        if "recommendation" not in tool_result:
            raise MalformedToolResponse("recommendation is missing")
        recommendation = tool_result["recommendation"]
        simulated_total += scenario["latency"][3]
        result = {"status": "success", "scenario": scenario_name, "trace_id": trace_id, "recommendation": recommendation}
    except AgentFailure as exc:
        result = {"status": "error", "scenario": scenario_name, "trace_id": trace_id, "error_type": type(exc).__name__}
    result["simulated_latency_ms"] = simulated_total
    result["wall_duration_ms"] = round((perf_counter() - started) * 1000, 3)
    return result


def read_spans(path=TRACE_PATH):
    # Step 3 replaces this placeholder with the JSONL reader.
    return []
  • Paste Chunk 6 directly below Chunk 5:

def reset_trace(path=TRACE_PATH):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("", encoding="utf-8")


def print_result(result, legacy=False):
    if result["status"] == "success":
        print(f"status=success scenario={result['scenario']} trace_id={result['trace_id']} recommendation={result['recommendation']}")
    elif legacy:
        print("status=error message=Agent failed")
    else:
        print(f"status=error scenario={result['scenario']} error={result['error_type']} trace_id={result['trace_id']}")


def main():
    parser = argparse.ArgumentParser(description="Local AI agent flight recorder")
    subparsers = parser.add_subparsers(dest="command", required=True)
    for command in ("legacy", "trace"):
        command_parser = subparsers.add_parser(command)
        command_parser.add_argument("scenario", choices=sorted(SCENARIOS))
        if command == "trace":
            command_parser.add_argument("--repair", action="store_true")
    subparsers.add_parser("reset")
    secret_parser = subparsers.add_parser("secret")
    secret_parser.add_argument("--runs", type=int, default=6)
    args = parser.parse_args()
  • Paste Chunk 7 directly below Chunk 6. This completes flight_recorder.py:

    if args.command == "reset":
        reset_trace()
        print(f"reset={TRACE_PATH}")
    elif args.command == "legacy":
        print_result(run_agent(args.scenario, NullRecorder()), legacy=True)
    elif args.command == "trace":
        recorder = FlightRecorder()
        result = run_agent(args.scenario, recorder, repaired=args.repair)
        recorder.close()
        print_result(result)
    elif args.command == "secret":
        reset_trace()
        recorder = FlightRecorder()
        results = [run_agent("flaky_timeout", recorder, repaired=True, run_number=number) for number in range(1, args.runs + 1)]
        recorder.close()
        successes = sum(result["status"] == "success" for result in results)
        print(f"runs={args.runs} successes={successes} failures={args.runs - successes} trace_file={TRACE_PATH}")


if __name__ == "__main__":
    main()

✔️ I pasted all seven chunks

Save flight_recorder.py. The next files are short enough to paste as complete files.

ⓧ I'd like to double check the full file

Compare your assembled file with this complete copy. Every line below matches Chunks 1 through 7 in order.

import argparse
import json
import logging
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from secrets import token_hex
from time import perf_counter

from retry_policy import should_retry

TRACE_PATH = Path("traces/agent.jsonl")
RECOVERY_SCENARIOS = ["password_reset", "shipping_delay", "warranty_question", "refund_route"]
SCENARIOS = {
    "password_reset": {"category": "password", "expected_tool": "knowledge_search", "latency": [4, 8, 18, 5]},
    "shipping_delay": {"category": "shipping", "expected_tool": "order_lookup", "latency": [4, 7, 24, 5]},
    "warranty_question": {"category": "warranty", "expected_tool": "knowledge_search", "latency": [3, 9, 16, 6]},
    "refund_route": {"category": "refund", "expected_tool": "billing_lookup", "latency": [4, 8, 20, 5]},
    "timeout_probe": {"category": "password", "expected_tool": "knowledge_search", "latency": [4, 8, 50, 0], "failure": "timeout"},
    "malformed_probe": {"category": "warranty", "expected_tool": "knowledge_search", "latency": [3, 9, 15, 0], "failure": "malformed"},
    "flaky_timeout": {"category": "password", "expected_tool": "knowledge_search", "latency": [3, 6, 30, 4], "failure": "every_third_timeout"},
}


class AgentFailure(RuntimeError):
    pass


class IncorrectRoute(AgentFailure):
    pass


class ToolTimeout(AgentFailure):
    pass


class MalformedToolResponse(AgentFailure):
    pass


def utc_now():
    return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")


class JsonlFormatter(logging.Formatter):
    def format(self, record):
        # Step 3 replaces this placeholder with JSON serialization.
        return record.getMessage()


class FlightRecorder:
    def __init__(self, path=TRACE_PATH):
        self.path = Path(path)
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.logger = logging.getLogger(f"flight-recorder.{token_hex(4)}")
        self.logger.setLevel(logging.INFO)
        self.logger.propagate = False
        self.handler = logging.FileHandler(self.path, encoding="utf-8")
        self.handler.setFormatter(JsonlFormatter())
        self.logger.addHandler(self.handler)

    def new_trace(self):
        return token_hex(16)

    @contextmanager
    def span(self, operation, trace_id, parent_span_id=None, attributes=None):
        # Step 3 turns this placeholder into a completed JSONL span.
        yield {"span_id": token_hex(8), "attributes": dict(attributes or {}), "simulated_latency_ms": 0}

    def close(self):
        self.logger.removeHandler(self.handler)
        self.handler.close()


class NullRecorder:
    def new_trace(self):
        return token_hex(16)

    @contextmanager
    def span(self, operation, trace_id, parent_span_id=None, attributes=None):
        yield {"span_id": token_hex(8), "attributes": dict(attributes or {}), "simulated_latency_ms": 0}


def select_tool(category, repaired):
    buggy_routes = {"password": "knowledge_search", "shipping": "order_lookup", "warranty": "knowledge_search", "refund": "knowledge_search"}
    repaired_routes = {**buggy_routes, "refund": "billing_lookup"}
    return (repaired_routes if repaired else buggy_routes)[category]


def retrieve_context(scenario_name):
    return f"support context for {scenario_name}"


def call_tool(scenario_name, selected_tool, run_number, attempt):
    scenario = SCENARIOS[scenario_name]
    if selected_tool != scenario["expected_tool"]:
        raise IncorrectRoute(f"expected {scenario['expected_tool']}, got {selected_tool}")
    failure = scenario.get("failure")
    if failure == "timeout":
        raise ToolTimeout("simulated tool deadline exceeded")
    if failure == "malformed":
        raise MalformedToolResponse("simulated response has no recommendation")
    if failure == "every_third_timeout" and run_number % 3 == 0 and attempt == 1:
        raise ToolTimeout("simulated every-third-run timeout")
    return {"recommendation": f"Use {selected_tool} evidence for {scenario_name}."}


def run_agent(scenario_name, recorder, repaired=False, run_number=1):
    scenario = SCENARIOS[scenario_name]
    trace_id = recorder.new_trace()
    started = perf_counter()
    simulated_total = 0
    try:
        selected_tool = select_tool(scenario["category"], repaired)
        context = retrieve_context(scenario_name)
        simulated_total += scenario["latency"][0] + scenario["latency"][1]
        attempt = 1
        while True:
            try:
                tool_result = call_tool(scenario_name, selected_tool, run_number, attempt)
                simulated_total += scenario["latency"][2]
                break
            except AgentFailure as exc:
                if should_retry(type(exc).__name__, attempt, selected_tool):
                    attempt += 1
                    continue
                raise
        if "recommendation" not in tool_result:
            raise MalformedToolResponse("recommendation is missing")
        recommendation = tool_result["recommendation"]
        simulated_total += scenario["latency"][3]
        result = {"status": "success", "scenario": scenario_name, "trace_id": trace_id, "recommendation": recommendation}
    except AgentFailure as exc:
        result = {"status": "error", "scenario": scenario_name, "trace_id": trace_id, "error_type": type(exc).__name__}
    result["simulated_latency_ms"] = simulated_total
    result["wall_duration_ms"] = round((perf_counter() - started) * 1000, 3)
    return result


def read_spans(path=TRACE_PATH):
    # Step 3 replaces this placeholder with the JSONL reader.
    return []


def reset_trace(path=TRACE_PATH):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("", encoding="utf-8")


def print_result(result, legacy=False):
    if result["status"] == "success":
        print(f"status=success scenario={result['scenario']} trace_id={result['trace_id']} recommendation={result['recommendation']}")
    elif legacy:
        print("status=error message=Agent failed")
    else:
        print(f"status=error scenario={result['scenario']} error={result['error_type']} trace_id={result['trace_id']}")


def main():
    parser = argparse.ArgumentParser(description="Local AI agent flight recorder")
    subparsers = parser.add_subparsers(dest="command", required=True)
    for command in ("legacy", "trace"):
        command_parser = subparsers.add_parser(command)
        command_parser.add_argument("scenario", choices=sorted(SCENARIOS))
        if command == "trace":
            command_parser.add_argument("--repair", action="store_true")
    subparsers.add_parser("reset")
    secret_parser = subparsers.add_parser("secret")
    secret_parser.add_argument("--runs", type=int, default=6)
    args = parser.parse_args()

    if args.command == "reset":
        reset_trace()
        print(f"reset={TRACE_PATH}")
    elif args.command == "legacy":
        print_result(run_agent(args.scenario, NullRecorder()), legacy=True)
    elif args.command == "trace":
        recorder = FlightRecorder()
        result = run_agent(args.scenario, recorder, repaired=args.repair)
        recorder.close()
        print_result(result)
    elif args.command == "secret":
        reset_trace()
        recorder = FlightRecorder()
        results = [run_agent("flaky_timeout", recorder, repaired=True, run_number=number) for number in range(1, args.runs + 1)]
        recorder.close()
        successes = sum(result["status"] == "success" for result in results)
        print(f"runs={args.runs} successes={successes} failures={args.runs - successes} trace_file={TRACE_PATH}")


if __name__ == "__main__":
    main()
  • Replace the entire contents of retry_policy.py with this baseline policy:
def should_retry(error_type: str, attempt: int, operation: str) -> bool:
    """Baseline policy. The Secret Mission replaces this no-retry behavior."""
    return False
  • Replace the entire contents of viewer.py with this initial server shell:
from fastapi import FastAPI

# Step 4 replaces this shell with the trace timeline.
app = FastAPI(title="AI Agent Flight Recorder")
  • Replace the entire contents of requirements.txt with these pinned dependencies:
fastapi[standard-no-fastapi-cloud-cli]==0.162.0
pytest==9.2.0
  • Replace the entire contents of .gitignore with these local exclusions:
.venv/
__pycache__/
.pytest_cache/
*.pyc
traces/*.jsonl
  • Replace the entire contents of README.md with this workshop note:
# AI Agent Flight Recorder

A local workshop project for tracing deterministic AI agent runs.

## Status

The opaque baseline is ready. Later steps add JSONL spans, a timeline, and tests.
  • Save every open file by clicking File and selecting Save All.
  • Confirm that the Explorer lists all six files inside ai-agent-flight-recorder.

A file is missing or nested?

Each filename must appear directly under ai-agent-flight-recorder. Move any file created inside another file or folder back to the top level.

If a pasted chunk reports indentation problems later, help me compare my assembled flight_recorder.py.

Set up the Python environment

All required source files now exist. The first terminal command checks whether your interpreter can run the project.

  • Open VS Code's terminal by clicking Terminal in the top menu.
  • Click New Terminal.
  • Check the Python version by running:
python --version

✔️ I see version 3.11 or higher

Your interpreter meets the project baseline. Continue with the platform tab below.

ⓧ I see an older version

Try python3 --version on macOS or Linux. On Windows, try py -3.11 --version.

If neither command reports Python 3.11 or newer, install a current release from the official Python downloads page. Restart VS Code before checking again.

ⓧ Command not found

Try python3 --version on macOS or Linux. On Windows, try py -3.11 --version.

If both platform commands fail, install Python from the official Python downloads page. Restart VS Code before continuing.

Create and activate .venv with the tab for your operating system.

macOS

  • Create the environment with Python 3 by running:
python3 -m venv .venv
  • Activate the environment by running:
source .venv/bin/activate

Windows

  • Create the environment with Python 3.11 by running:
py -3.11 -m venv .venv
  • Activate the environment in PowerShell by running:
.venv\Scripts\Activate.ps1
PowerShell blocked activation?

Activation is optional. Use .venv\Scripts\python.exe instead of python in the install and run commands below.

Linux

  • Create the environment with Python 3 by running:
python3 -m venv .venv
  • Activate the environment by running:
source .venv/bin/activate
The venv module is unavailable?

Install your distribution's Python virtual-environment package for Python 3.11 or newer. Then repeat the environment command.

For distribution-specific help, help me install Python venv on Linux.

Your terminal prompt should now include .venv. The Explorer also shows the new environment folder.

Install dependencies and run the baseline
  • Install the pinned dependencies by running:
python -m pip install -r requirements.txt

The first install can take a minute while pip downloads FastAPI and pytest. It should finish without a dependency error.

Dependency installation failed?

Confirm that the terminal prompt includes .venv and that requirements.txt contains exactly two lines. On Windows with blocked activation, run .venv\Scripts\python.exe -m pip install -r requirements.txt instead.

If the error continues, help me debug the dependency installation.

Before you run the agent, do you expect the prepared password reset request to succeed or fail?

  • Run the healthy baseline scenario with:
python flight_recorder.py legacy password_reset

You should see one line beginning with status=success scenario=password_reset and containing Use knowledge_search evidence for password_reset. The trace ID varies on each run.

The baseline did not run?

  • Confirm that the terminal path ends with ai-agent-flight-recorder.
  • Confirm that every file in the Explorer is saved.
  • Confirm that retry_policy.py is beside flight_recorder.py.

Windows learners with blocked activation can run .venv\Scripts\python.exe flight_recorder.py legacy password_reset. If the command still fails, help me debug the self-contained baseline.

Your self-contained baseline now runs without an external starter asset. Next, you will expose how little that healthy output reveals when another request fails.

Reproduce the Opaque Failure

Your starter agent already returns a successful password-reset recommendation. That baseline proves the local environment can execute the workflow.

Now you need to test what the legacy output reveals when a refund request takes a different path. The crucial question is whether the terminal identifies what happened inside the run.

In this step, get ready to:
  • Reconfirm the healthy password-reset baseline.
  • Run the refund scenario twice to test its repeatability.
  • Audit the diagnostic evidence exposed by the legacy output.
Reconfirm the healthy baseline

A known healthy scenario gives you a comparison point. Its output shows what the legacy interface reports when the workflow reaches a recommendation.

  • Return to the integrated terminal in VS Code from the previous step.
  • Run the known healthy scenario with the active project environment:
python flight_recorder.py legacy password_reset

What Does This Run Prove?

This command reruns the known healthy scenario through the legacy interface. It confirms that your environment remains ready for a controlled comparison.

You should see a line containing status=success. The recommendation should reference knowledge_search evidence for password_reset.

Your baseline is steady: the password-reset path still reaches a recommendation.

Baseline Result Changed?

  • Confirm that you returned to the terminal used in the previous step.
  • Confirm that the terminal folder contains flight_recorder.py.
  • Use the same Python interpreter that produced the earlier successful result.

If the result changed, help me diagnose the healthy password reset run.

Trigger the refund path twice

A single run can leave uncertainty about repeatability. Two identical inputs show whether the behavior stays consistent.

Before you run these commands, do you expect both refund requests to produce matching terminal evidence?

  • Run the refund scenario twice by running these commands:
python flight_recorder.py legacy refund_route
python flight_recorder.py legacy refund_route

What Does This Comparison Reveal?

Both executions print only status=error message=Agent failed. The matching result proves that the refund behavior is reproducible.

The generic line gives you no internal evidence about the route or failing operation. Repetition confirms the problem without explaining its cause.

  • Review the two refund outputs in the terminal history.

You should see two matching refund error lines beneath the healthy baseline output.

Refund Outputs Do Not Match?

  • Confirm that both commands use the refund_route scenario.
  • Confirm that both commands use the legacy mode.
  • Rerun only the command whose output differs from the expected generic error.

Ask for help comparing the runs: help me investigate why my two legacy refund runs produce different results

Audit the missing evidence

Useful observability evidence connects a final outcome to the operations that produced it. The legacy error leaves that execution story hidden.

What Is Missing From the Legacy Output?

  • No operation name identifies the failing stage.
  • No selected_tool value reveals the routing decision.
  • No trace correlation connects the work performed during one run.
  • No error_type value distinguishes the failure cause.
  • No simulated_latency_ms value exposes the scenario timing.
  • No wall_duration_ms value exposes the measured local duration.
  • Compare the legacy error line with each evidence category above.

Every category remains unanswered. The legacy line reports only that the agent failed.

Your refund failure is reproducible. Next, you will replace the generic line with correlated JSONL spans that identify the failing operation.

Record Correlated JSONL Spans

Two identical refund failures have proved that the agent can fail reproducibly without producing useful diagnostic evidence. The legacy output still hides the operation that caused the failure.

A trace connects one agent run to its nested spans. You will record each completed span as one structured JSONL row.

In this step, get ready to:
  • Implement the recorder that writes completed spans to a local trace file.
  • Instrument the agent operations with shared trace correlation.
  • Reproduce the refund failure with operation-level evidence.
Build the span recorder

Each line in the trace file represents one finished operation. The recorder writes the line after the operation succeeds or raises an error.

  • In flight_recorder.py, locate the existing JsonlFormatter class.
  • Replace that class with the code below:
class JsonlFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        payload = record.msg if isinstance(record.msg, dict) else {"message": record.getMessage()}
        return json.dumps(payload, sort_keys=True)

What does this formatter do?

  • JsonlFormatter accepts the span dictionary attached to a log record.
  • json.dumps() serializes that dictionary as one sorted JSON object.
  • Each logging call therefore becomes one JSONL row.
  • Locate new_trace() inside the existing FlightRecorder class.
  • Replace new_trace(), span(), and close() with the following methods:
    def new_trace(self) -> str:
        return token_hex(16)
    @contextmanager
    def span(self, operation: str, trace_id: str, parent_span_id: str | None = None, attributes: dict | None = None):
        span_id = token_hex(8)
        started_at = utc_now()
        started_counter = perf_counter()
        data = {"span_id": span_id, "attributes": dict(attributes or {}), "simulated_latency_ms": 0}
        event = {"trace_id": trace_id, "span_id": span_id, "parent_span_id": parent_span_id, "operation": operation, "started_at": started_at, "status": "OK", "attributes": data["attributes"], "error_type": None, "error_message": None}
        try:
            yield data
        except Exception as exc:
            event["status"] = "ERROR"
            event["error_type"] = type(exc).__name__
            event["error_message"] = str(exc)
            raise
        finally:
            event["ended_at"] = utc_now()
            event["wall_duration_ms"] = round((perf_counter() - started_counter) * 1000, 3)
            event["simulated_latency_ms"] = data["simulated_latency_ms"]
            self.logger.info(event)
    def close(self) -> None:
        self.logger.removeHandler(self.handler)
        self.handler.close()

How does a span preserve evidence?

  • new_trace() generates 16 random bytes as a 32-character hexadecimal trace ID.
  • span() generates eight random bytes as a 16-character hexadecimal span ID.
  • yield lets the wrapped operation add attributes and simulated latency.
  • finally records timing evidence for successful operations and failed operations.
  • Save flight_recorder.py.
  • Check the editor for red syntax underlines inside FlightRecorder.

Legacy execution needs the same recorder interface without writing trace rows. A null recorder preserves that interface while discarding the completed span data.

  • Locate the existing NullRecorder class in flight_recorder.py.
  • Replace that class with the code below:
class NullRecorder:
    def new_trace(self) -> str:
        return token_hex(16)
    @contextmanager
    def span(self, operation: str, trace_id: str, parent_span_id: str | None = None, attributes: dict | None = None):
        yield {"span_id": token_hex(8), "attributes": dict(attributes or {}), "simulated_latency_ms": 0}

Why keep a null recorder?

NullRecorder exposes the same new_trace() and span() methods as FlightRecorder. The agent can switch recording behavior without changing its workflow logic.

  • Save flight_recorder.py.
  • Confirm that the legacy happy path still runs by executing this command:
python flight_recorder.py legacy password_reset

You should see a successful recommendation for password_reset. This confirms that the null recorder still supports the original execution path.

Seeing a recorder error?

Confirm that both recorder classes define new_trace() and span(). Check that @contextmanager sits directly above each span() method.

help me compare the FlightRecorder and NullRecorder interfaces

Instrument the agent workflow

The root agent.run span owns one trace ID. Every nested operation receives the root span ID through parent_span_id.

  • Locate the complete run_agent() function in flight_recorder.py.
  • Delete that entire function, from its def run_agent line through return result.
  • Paste Chunk 1 below in the empty location:
def run_agent(scenario_name: str, recorder: FlightRecorder | NullRecorder, repaired: bool = False, run_number: int = 1) -> dict:
    scenario = SCENARIOS[scenario_name]
    trace_id = recorder.new_trace()
    started = perf_counter()
    simulated_total = 0
    try:
        with recorder.span("agent.run", trace_id, attributes={"scenario": scenario_name, "run_number": run_number}) as root:
            try:
                with recorder.span("route_issue", trace_id, root["span_id"]) as route_span:
                    selected_tool = select_tool(scenario["category"], repaired)
                    route_span["attributes"]["selected_tool"] = selected_tool
                    route_span["simulated_latency_ms"] = scenario["latency"][0]
                    simulated_total += scenario["latency"][0]
                with recorder.span("retrieve_context", trace_id, root["span_id"]) as retrieval_span:
                    context = retrieve_context(scenario_name)
                    retrieval_span["attributes"]["context_chars"] = len(context)
                    retrieval_span["simulated_latency_ms"] = scenario["latency"][1]
                    simulated_total += scenario["latency"][1]

How does correlation begin?

  • trace_id remains constant for the complete agent run.
  • root["span_id"] becomes the parent ID for each nested operation.
  • route_issue records the selected tool as a diagnostic attribute.
  • retrieve_context records the number of retrieved context characters.
  • Paste Chunk 2 directly below Chunk 1 without changing its leading spaces.
  • Confirm that the next top-level function begins only after Chunk 2's return result line.
                attempt = 1
                while True:
                    try:
                        with recorder.span("call_tool", trace_id, root["span_id"], {"selected_tool": selected_tool, "attempt": attempt}) as tool_span:
                            tool_span["simulated_latency_ms"] = scenario["latency"][2]
                            simulated_total += scenario["latency"][2]
                            tool_result = call_tool(scenario_name, selected_tool, run_number, attempt)
                        break
                    except AgentFailure as exc:
                        if should_retry(type(exc).__name__, attempt, selected_tool):
                            attempt += 1
                            continue
                        raise
                with recorder.span("compose_recommendation", trace_id, root["span_id"]) as compose_span:
                    if "recommendation" not in tool_result:
                        raise MalformedToolResponse("recommendation is missing")
                    recommendation = tool_result["recommendation"]
                    compose_span["simulated_latency_ms"] = scenario["latency"][3]
                    simulated_total += scenario["latency"][3]
            finally:
                root["simulated_latency_ms"] = simulated_total
        result = {"status": "success", "scenario": scenario_name, "trace_id": trace_id, "recommendation": recommendation}
    except AgentFailure as exc:
        result = {"status": "error", "scenario": scenario_name, "trace_id": trace_id, "error_type": type(exc).__name__}
    result["simulated_latency_ms"] = simulated_total
    result["wall_duration_ms"] = round((perf_counter() - started) * 1000, 3)
    return result

How does the failure become diagnosable?

  • call_tool records the selected tool and the current attempt number.
  • compose_recommendation receives its own child span after a successful tool response.
  • simulated_total accumulates deterministic scenario latency for the root span.
  • perf_counter() measures local elapsed time independently from that scenario data.
  • Save flight_recorder.py.
  • Run the legacy happy path again to check the instrumented workflow:
python flight_recorder.py legacy password_reset

You should still see status=success with a recommendation. The instrumented workflow remains compatible with legacy mode.

Seeing a syntax error in run_agent?

Check that the second code chunk starts inside the inner try block. Confirm that return result aligns with the first statement inside the function.

help me repair the run_agent block structure

Reproduce the traced failure

A controlled reproduction needs a clean trace file and a way to parse its rows. Resetting first ensures that every row belongs to the refund run you are investigating.

  • Locate the existing read_spans() function in flight_recorder.py.
  • Replace that function with the code below:
def read_spans(path: Path = TRACE_PATH) -> list[dict]:
    path = Path(path)
    if not path.exists(): return []
    return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]

What does the reader return?

read_spans() parses each nonempty JSONL line independently. Later code can group the resulting dictionaries by their shared trace ID.

  • Locate the existing reset_trace() function in flight_recorder.py.
  • Replace that function with the code below:
def reset_trace(path: Path = TRACE_PATH) -> None:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("", encoding="utf-8")

Why reset the trace file?

reset_trace() creates the trace directory when needed. It empties the trace file before a controlled reproduction.

  • Save flight_recorder.py.

Before you run the traced scenario, which missing details do you expect the recorder to add to the generic failure?

  • Reset the trace file and reproduce the unrepaired refund failure by running these commands:
python flight_recorder.py reset
python flight_recorder.py trace refund_route

What do these commands prove?

The first command clears traces/agent.jsonl. The second command runs the refund scenario through FlightRecorder.

The terminal now names IncorrectRoute and prints a trace ID. The trace file preserves the operation-level evidence behind that result.

  • Switch back to the Explorer sidebar in VS Code.
  • Select traces/agent.jsonl.
  • Confirm that every row has the same 32-character trace_id.
  • Confirm that every row has a unique 16-character span_id.
  • Compare each child parent_span_id with the agent.run span ID.
  • Find the route_issue row with knowledge_search stored under selected_tool.
  • Find the call_tool row with ERROR status.
  • Confirm that the failing row records IncorrectRoute with attempt 1.

That is the black box opened. You can identify the selected tool and the first failing operation without inspecting the routing source.

Why are there two latency fields?

simulated_latency_ms stores deterministic scenario data. It remains stable across workshop machines.

wall_duration_ms stores measured local elapsed time. It can vary because each computer executes the workflow at a different speed.

🙋‍♀️ Missing trace rows?

Confirm that you saved flight_recorder.py before running the commands. Check that self.logger.info(event) remains inside the finally block.

help me diagnose missing or uncorrelated JSONL spans

✔️ Awesome, I've got everything!

Your refund trace now preserves the selected tool and the first failing operation. Double check that flight_recorder.py is saved before moving on.

ⓧ I'd like to double check the full code

Compare your completed flight_recorder.py with this cumulative version.

import argparse
import json
import logging
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from secrets import token_hex
from time import perf_counter

from retry_policy import should_retry

TRACE_PATH = Path("traces/agent.jsonl")
RECOVERY_SCENARIOS = ["password_reset", "shipping_delay", "warranty_question", "refund_route"]
SCENARIOS = {
    "password_reset": {"category": "password", "expected_tool": "knowledge_search", "latency": [4, 8, 18, 5]},
    "shipping_delay": {"category": "shipping", "expected_tool": "order_lookup", "latency": [4, 7, 24, 5]},
    "warranty_question": {"category": "warranty", "expected_tool": "knowledge_search", "latency": [3, 9, 16, 6]},
    "refund_route": {"category": "refund", "expected_tool": "billing_lookup", "latency": [4, 8, 20, 5]},
    "timeout_probe": {"category": "password", "expected_tool": "knowledge_search", "latency": [4, 8, 50, 0], "failure": "timeout"},
    "malformed_probe": {"category": "warranty", "expected_tool": "knowledge_search", "latency": [3, 9, 15, 0], "failure": "malformed"},
    "flaky_timeout": {"category": "password", "expected_tool": "knowledge_search", "latency": [3, 6, 30, 4], "failure": "every_third_timeout"},
}


class AgentFailure(RuntimeError):
    pass


class IncorrectRoute(AgentFailure):
    pass


class ToolTimeout(AgentFailure):
    pass


class MalformedToolResponse(AgentFailure):
    pass


def utc_now():
    return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")


class JsonlFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        payload = record.msg if isinstance(record.msg, dict) else {"message": record.getMessage()}
        return json.dumps(payload, sort_keys=True)


class FlightRecorder:
    def __init__(self, path=TRACE_PATH):
        self.path = Path(path)
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.logger = logging.getLogger(f"flight-recorder.{token_hex(4)}")
        self.logger.setLevel(logging.INFO)
        self.logger.propagate = False
        self.handler = logging.FileHandler(self.path, encoding="utf-8")
        self.handler.setFormatter(JsonlFormatter())
        self.logger.addHandler(self.handler)

    def new_trace(self) -> str:
        return token_hex(16)

    @contextmanager
    def span(self, operation: str, trace_id: str, parent_span_id: str | None = None, attributes: dict | None = None):
        span_id = token_hex(8)
        started_at = utc_now()
        started_counter = perf_counter()
        data = {"span_id": span_id, "attributes": dict(attributes or {}), "simulated_latency_ms": 0}
        event = {"trace_id": trace_id, "span_id": span_id, "parent_span_id": parent_span_id, "operation": operation, "started_at": started_at, "status": "OK", "attributes": data["attributes"], "error_type": None, "error_message": None}
        try:
            yield data
        except Exception as exc:
            event["status"] = "ERROR"
            event["error_type"] = type(exc).__name__
            event["error_message"] = str(exc)
            raise
        finally:
            event["ended_at"] = utc_now()
            event["wall_duration_ms"] = round((perf_counter() - started_counter) * 1000, 3)
            event["simulated_latency_ms"] = data["simulated_latency_ms"]
            self.logger.info(event)

    def close(self) -> None:
        self.logger.removeHandler(self.handler)
        self.handler.close()


class NullRecorder:
    def new_trace(self) -> str:
        return token_hex(16)

    @contextmanager
    def span(self, operation: str, trace_id: str, parent_span_id: str | None = None, attributes: dict | None = None):
        yield {"span_id": token_hex(8), "attributes": dict(attributes or {}), "simulated_latency_ms": 0}


def select_tool(category, repaired):
    buggy_routes = {"password": "knowledge_search", "shipping": "order_lookup", "warranty": "knowledge_search", "refund": "knowledge_search"}
    repaired_routes = {**buggy_routes, "refund": "billing_lookup"}
    return (repaired_routes if repaired else buggy_routes)[category]


def retrieve_context(scenario_name):
    return f"support context for {scenario_name}"


def call_tool(scenario_name, selected_tool, run_number, attempt):
    scenario = SCENARIOS[scenario_name]
    if selected_tool != scenario["expected_tool"]:
        raise IncorrectRoute(f"expected {scenario['expected_tool']}, got {selected_tool}")
    failure = scenario.get("failure")
    if failure == "timeout":
        raise ToolTimeout("simulated tool deadline exceeded")
    if failure == "malformed":
        raise MalformedToolResponse("simulated response has no recommendation")
    if failure == "every_third_timeout" and run_number % 3 == 0 and attempt == 1:
        raise ToolTimeout("simulated every-third-run timeout")
    return {"recommendation": f"Use {selected_tool} evidence for {scenario_name}."}


def run_agent(scenario_name: str, recorder: FlightRecorder | NullRecorder, repaired: bool = False, run_number: int = 1) -> dict:
    scenario = SCENARIOS[scenario_name]
    trace_id = recorder.new_trace()
    started = perf_counter()
    simulated_total = 0
    try:
        with recorder.span("agent.run", trace_id, attributes={"scenario": scenario_name, "run_number": run_number}) as root:
            try:
                with recorder.span("route_issue", trace_id, root["span_id"]) as route_span:
                    selected_tool = select_tool(scenario["category"], repaired)
                    route_span["attributes"]["selected_tool"] = selected_tool
                    route_span["simulated_latency_ms"] = scenario["latency"][0]
                    simulated_total += scenario["latency"][0]
                with recorder.span("retrieve_context", trace_id, root["span_id"]) as retrieval_span:
                    context = retrieve_context(scenario_name)
                    retrieval_span["attributes"]["context_chars"] = len(context)
                    retrieval_span["simulated_latency_ms"] = scenario["latency"][1]
                    simulated_total += scenario["latency"][1]
                attempt = 1
                while True:
                    try:
                        with recorder.span("call_tool", trace_id, root["span_id"], {"selected_tool": selected_tool, "attempt": attempt}) as tool_span:
                            tool_span["simulated_latency_ms"] = scenario["latency"][2]
                            simulated_total += scenario["latency"][2]
                            tool_result = call_tool(scenario_name, selected_tool, run_number, attempt)
                        break
                    except AgentFailure as exc:
                        if should_retry(type(exc).__name__, attempt, selected_tool):
                            attempt += 1
                            continue
                        raise
                with recorder.span("compose_recommendation", trace_id, root["span_id"]) as compose_span:
                    if "recommendation" not in tool_result:
                        raise MalformedToolResponse("recommendation is missing")
                    recommendation = tool_result["recommendation"]
                    compose_span["simulated_latency_ms"] = scenario["latency"][3]
                    simulated_total += scenario["latency"][3]
            finally:
                root["simulated_latency_ms"] = simulated_total
        result = {"status": "success", "scenario": scenario_name, "trace_id": trace_id, "recommendation": recommendation}
    except AgentFailure as exc:
        result = {"status": "error", "scenario": scenario_name, "trace_id": trace_id, "error_type": type(exc).__name__}
    result["simulated_latency_ms"] = simulated_total
    result["wall_duration_ms"] = round((perf_counter() - started) * 1000, 3)
    return result


def read_spans(path: Path = TRACE_PATH) -> list[dict]:
    path = Path(path)
    if not path.exists():
        return []
    return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]


def reset_trace(path: Path = TRACE_PATH) -> None:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("", encoding="utf-8")


def print_result(result, legacy=False):
    if result["status"] == "success":
        print(f"status=success scenario={result['scenario']} trace_id={result['trace_id']} recommendation={result['recommendation']}")
    elif legacy:
        print("status=error message=Agent failed")
    else:
        print(f"status=error scenario={result['scenario']} error={result['error_type']} trace_id={result['trace_id']}")


def main():
    parser = argparse.ArgumentParser(description="Local AI agent flight recorder")
    subparsers = parser.add_subparsers(dest="command", required=True)
    for command in ("legacy", "trace"):
        command_parser = subparsers.add_parser(command)
        command_parser.add_argument("scenario", choices=sorted(SCENARIOS))
        if command == "trace":
            command_parser.add_argument("--repair", action="store_true")
    subparsers.add_parser("reset")
    secret_parser = subparsers.add_parser("secret")
    secret_parser.add_argument("--runs", type=int, default=6)
    args = parser.parse_args()

    if args.command == "reset":
        reset_trace()
        print(f"reset={TRACE_PATH}")
    elif args.command == "legacy":
        print_result(run_agent(args.scenario, NullRecorder()), legacy=True)
    elif args.command == "trace":
        recorder = FlightRecorder()
        result = run_agent(args.scenario, recorder, repaired=args.repair)
        recorder.close()
        print_result(result)
    elif args.command == "secret":
        reset_trace()
        recorder = FlightRecorder()
        results = [run_agent("flaky_timeout", recorder, repaired=True, run_number=number) for number in range(1, args.runs + 1)]
        recorder.close()
        successes = sum(result["status"] == "success" for result in results)
        print(f"runs={args.runs} successes={successes} failures={args.runs - successes} trace_file={TRACE_PATH}")


if __name__ == "__main__":
    main()

Your retry_policy.py file should still contain the starter no-retry policy.

def should_retry(error_type: str, attempt: int, operation: str) -> bool:
    """Baseline policy. The Secret Mission replaces this no-retry behavior."""
    return False

Your pinned dependencies should still match this requirements.txt file.

fastapi[standard-no-fastapi-cloud-cli]==0.162.0
pytest==9.2.0

Your agent now leaves structured evidence behind every traced run. Next, you will turn those JSONL rows into a local timeline that makes the broken route faster to diagnose.

Inspect the Trace Timeline

Your JSONL records now contain enough evidence to explain the refund failure. Reading separate rows still makes the execution hierarchy slow to reconstruct.

This step turns those records into a local FastAPI timeline. You will use the timeline to identify the incorrect route without opening select_tool().

In this step, get ready to:
  • Build a local timeline that groups correlated spans by trace.
  • Launch the timeline at http://127.0.0.1:8000.
  • Diagnose the refund failure from trace evidence.
Build the timeline foundation

The viewer needs a web application plus a small style layer before it can present trace data. It also imports the existing trace reader so the browser always reflects traces/agent.jsonl.

  • Open the existing viewer.py file beside flight_recorder.py in the VS Code Explorer.
  • Select every line in viewer.py and delete the initial server shell.
  • Paste the viewer foundation below into the empty file:
import html
import json
from collections import defaultdict
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from flight_recorder import read_spans

app = FastAPI(title="AI Agent Flight Recorder")
STYLE = """<style>body{font-family:system-ui,sans-serif;margin:2rem;background:#f5f7fb;color:#172033}header{display:flex;justify-content:space-between;align-items:center}.trace{background:white;border-radius:12px;padding:1rem;margin:1rem 0;box-shadow:0 2px 10px #dfe5ef}table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:.55rem;border-bottom:1px solid #e6eaf0;vertical-align:top}.OK{color:#116329;font-weight:700}.ERROR{color:#b42318;font-weight:700}.child{padding-left:1.6rem}code{font-size:.78rem}button{padding:.5rem .8rem}</style>"""

What does the viewer foundation do?

  • The html module provides the escaping function that protects rendered trace content.
  • The json module converts attribute dictionaries into readable strings.
  • The defaultdict collection groups spans under their shared trace IDs.
  • The read_spans() function loads the records already stored in traces/agent.jsonl.
  • The STYLE string gives the timeline its CSS layout.
  • Save viewer.py.
  • Confirm that viewer.py remains beside flight_recorder.py in the ai-agent-flight-recorder folder.

You should see viewer.py beside flight_recorder.py.

Cannot find viewer.py?

  • Check that you created viewer.py inside the same repository as flight_recorder.py.
  • Confirm the filename ends with .py.

Ask for help with locating the new viewer file.

Render and launch the timeline

The render_timeline() function converts finished spans into trace cards. It sorts operations by their start time so the page reconstructs the execution order.

Trace content can contain characters with special meaning in HTML. Escaping that content keeps scenario data inside the table cells where it belongs.

  • Place the following code below the STYLE definition in viewer.py:
def render_timeline() -> str:
    grouped = defaultdict(list)
    for span in read_spans(): grouped[span["trace_id"]].append(span)
    cards = []
    for trace_id, spans in reversed(list(grouped.items())):
        spans.sort(key=lambda span: span["started_at"])
        root = next(span for span in spans if span["operation"] == "agent.run")
        rows = []
        for span in spans:
            operation_class = "child" if span["parent_span_id"] else "root"
            error = f"{span['error_type']}: {span['error_message']}" if span["error_type"] else ""
            attributes = json.dumps(span["attributes"], sort_keys=True)
            rows.append("<tr>" f"<td class='{operation_class}'>{html.escape(span['operation'])}</td>" f"<td class='{span['status']}'>{span['status']}</td>" f"<td>{span['simulated_latency_ms']}</td>" f"<td>{span['wall_duration_ms']}</td>" f"<td><code>{html.escape(attributes)}</code></td>" f"<td>{html.escape(error)}</td></tr>")
        cards.append("<section class='trace'>" f"<h2>{html.escape(root['attributes']['scenario'])}</h2><p><code>{html.escape(trace_id)}</code></p>" "<table><thead><tr><th>Operation</th><th>Status</th><th>Simulated ms</th><th>Wall ms</th><th>Attributes</th><th>Error</th></tr></thead><tbody>" + "".join(rows) + "</tbody></table></section>")
    content = "".join(cards) if cards else "<p>No traces yet. Run a traced scenario and refresh.</p>"
    return "<!doctype html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>AI Agent Flight Recorder</title>" + STYLE + "</head><body><header><div><h1>AI Agent Flight Recorder</h1><p>Structured local execution timeline</p></div><button onclick='location.reload()'>Refresh</button></header>" + content + "</body></html>"

@app.get("/", response_class=HTMLResponse)
def timeline() -> str:
    return render_timeline()

How does the timeline work?

  • The shared trace_id places every operation from one agent run into the same card.
  • The started_at sort restores the operation order.
  • The parent_span_id field determines which operations receive the indented child style.
  • The html.escape() calls protect scenario names plus trace values before rendering them.
  • The / endpoint returns the complete timeline through HTMLResponse.
  • Save viewer.py.

Before you start the viewer, which operation do you expect the timeline to mark as the first failure?

  • Start the local timeline server from the existing project environment by running:
fastapi dev viewer.py

What does this command do?

The command loads viewer.py in development mode. The server exposes the timeline at http://127.0.0.1:8000.

  • Open http://127.0.0.1:8000 in your browser.

You should see an AI Agent Flight Recorder page with a refund_route card. Its table shows the operation order plus status, simulated timing, wall timing, attributes, and error evidence.

That is the raw refund trace turned into a readable execution timeline.

Timeline does not load?

  • Return to the terminal that uses your existing local Python environment.
  • Confirm no other local server is using port 8000.
  • Compare viewer.py with the complete file below for missing quotes or parentheses.

Ask for help with debugging the local FastAPI timeline.

✔️ Awesome, I've got everything!

Your timeline is running. Keep the server terminal active while you inspect the refund trace.

ⓧ I'd like to double check the full code

Compare your viewer.py with this complete version.

import html
import json
from collections import defaultdict
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from flight_recorder import read_spans

app = FastAPI(title="AI Agent Flight Recorder")
STYLE = """<style>body{font-family:system-ui,sans-serif;margin:2rem;background:#f5f7fb;color:#172033}header{display:flex;justify-content:space-between;align-items:center}.trace{background:white;border-radius:12px;padding:1rem;margin:1rem 0;box-shadow:0 2px 10px #dfe5ef}table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:.55rem;border-bottom:1px solid #e6eaf0;vertical-align:top}.OK{color:#116329;font-weight:700}.ERROR{color:#b42318;font-weight:700}.child{padding-left:1.6rem}code{font-size:.78rem}button{padding:.5rem .8rem}</style>"""

def render_timeline() -> str:
    grouped = defaultdict(list)
    for span in read_spans(): grouped[span["trace_id"]].append(span)
    cards = []
    for trace_id, spans in reversed(list(grouped.items())):
        spans.sort(key=lambda span: span["started_at"])
        root = next(span for span in spans if span["operation"] == "agent.run")
        rows = []
        for span in spans:
            operation_class = "child" if span["parent_span_id"] else "root"
            error = f"{span['error_type']}: {span['error_message']}" if span["error_type"] else ""
            attributes = json.dumps(span["attributes"], sort_keys=True)
            rows.append("<tr>" f"<td class='{operation_class}'>{html.escape(span['operation'])}</td>" f"<td class='{span['status']}'>{span['status']}</td>" f"<td>{span['simulated_latency_ms']}</td>" f"<td>{span['wall_duration_ms']}</td>" f"<td><code>{html.escape(attributes)}</code></td>" f"<td>{html.escape(error)}</td></tr>")
        cards.append("<section class='trace'>" f"<h2>{html.escape(root['attributes']['scenario'])}</h2><p><code>{html.escape(trace_id)}</code></p>" "<table><thead><tr><th>Operation</th><th>Status</th><th>Simulated ms</th><th>Wall ms</th><th>Attributes</th><th>Error</th></tr></thead><tbody>" + "".join(rows) + "</tbody></table></section>")
    content = "".join(cards) if cards else "<p>No traces yet. Run a traced scenario and refresh.</p>"
    return "<!doctype html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>AI Agent Flight Recorder</title>" + STYLE + "</head><body><header><div><h1>AI Agent Flight Recorder</h1><p>Structured local execution timeline</p></div><button onclick='location.reload()'>Refresh</button></header>" + content + "</body></html>"

@app.get("/", response_class=HTMLResponse)
def timeline() -> str:
    return render_timeline()
Diagnose the refund trace

A useful timeline identifies the decision that led to a failure. It also separates deterministic scenario data from measurements that change across machines.

Before you inspect the rows, which field do you expect will expose the wrong route?

  • Find the refund_route trace card.
  • Inspect the route_issue row.
  • Read the selected_tool attribute.
  • Locate the first child operation with an ERROR status.
  • Compare the simulated timing column with the wall timing column.

You should see that route_issue selected knowledge_search even though the refund scenario expected billing_lookup.

The first failing child operation is call_tool. Its error field reports IncorrectRoute.

The simulated_latency_ms values come from fixed scenario data. The wall_duration_ms values measure local execution and can vary by machine.

Your timeline now exposes the route decision plus the exact failing operation. Next, you will repair the route and prove the improvement with regression tests plus an observability report.

Repair the Route and Prove Observability

Your timeline exposed the wrong refund route without requiring you to inspect the routing source. The correlated JSONL evidence identified knowledge_search as the decision that led to the failure.

Now you will activate the repaired mapping and protect it with pytest regression tests. You will finish with an observability report that connects the change to trace evidence and deterministic latency.

In this step, get ready to:
  • Repair the refund route and confirm that it selects the billing tool.
  • Add regression tests for successful routes and diagnosable failures.
  • Create an observability report with before-and-after evidence.
Run the repaired refund route

The starter keeps the broken and repaired mappings side by side so you can compare them under the same conditions. The --repair flag switches the refund category from knowledge_search to billing_lookup.

  • Return to the terminal running the timeline server.
  • Stop the server by pressing Ctrl+C.

Before you run the repair, do you expect the refund trace to contain any operation with an ERROR status?

  • Reset the trace file and run the repaired refund scenario by executing these commands:
python flight_recorder.py reset
python flight_recorder.py trace refund_route --repair

What does the repair change?

  • The first command clears the earlier failing trace from traces/agent.jsonl.
  • The second command enables the repaired route mapping for this traced run.
  • The refund category now selects billing_lookup before the tool call begins.
  • The recorder preserves the successful decision under the same trace schema used for the failure.

You should see status=success scenario=refund_route with a recommendation containing Use billing_lookup evidence for refund_route. That is the broken path repaired under trace.

Repaired refund still fails?

  • Confirm that the command ends with --repair.
  • Check that select_tool() still maps the repaired refund route to billing_lookup.
  • Confirm that refund_route expects billing_lookup in SCENARIOS.

Ask for help with diagnosing the repaired refund run.

Build the regression suite

A successful manual run proves the repair once. Regression tests preserve that behavior while checking that trace evidence still explains genuine failures.

  • Click the Explorer icon in the left sidebar of VS Code.
  • Click the New File icon beside ai-agent-flight-recorder.
  • Enter test_flight_recorder.py.
  • Press Enter.
  • Add the imports and recovery regression test by pasting this code:
from flight_recorder import FlightRecorder, RECOVERY_SCENARIOS, read_spans, run_agent


def test_repaired_recovery_scenarios(tmp_path):
    # Isolate each repaired run in its own temporary trace file.
    for scenario_name in RECOVERY_SCENARIOS:
        trace_path = tmp_path / f"{scenario_name}.jsonl"
        recorder = FlightRecorder(trace_path)
        result = run_agent(scenario_name, recorder, repaired=True)
        recorder.close()
        spans = read_spans(trace_path)
        operations = {span["operation"] for span in spans}
        assert result["status"] == "success"
        assert {"agent.run", "route_issue", "call_tool", "compose_recommendation"} <= operations

What does the recovery test protect?

  • RECOVERY_SCENARIOS covers password reset, shipping delay, warranty, and refund requests.
  • tmp_path gives each scenario a separate temporary trace location.
  • The status assertion protects the repaired behavior.
  • The operation assertion protects the trace timeline needed to explain each run.
  • Save test_flight_recorder.py.
  • Run the first regression test by executing:
python -m pytest

You should see 1 passed in the test summary. The four repaired recovery scenarios now share one protected execution contract.

Recovery regression failed?

  • Confirm that repaired=True is passed to run_agent().
  • Check that each temporary filename uses scenario_name.
  • Compare the expected operation names with the strings recorded in run_agent().

Ask for help with debugging the recovery regression.

  • Place the refund routing test at the end of test_flight_recorder.py by pasting:
def test_refund_uses_billing_lookup(tmp_path):
    # Capture the route decision that fixes the original incident.
    trace_path = tmp_path / "refund.jsonl"
    recorder = FlightRecorder(trace_path)
    result = run_agent("refund_route", recorder, repaired=True)
    recorder.close()
    spans = read_spans(trace_path)
    route_span = next(span for span in spans if span["operation"] == "route_issue")
    assert result["status"] == "success"
    assert route_span["attributes"]["selected_tool"] == "billing_lookup"

Why test the recorded decision?

A successful status alone would miss a future routing change that happens to return a result. The trace assertion protects the exact billing_lookup decision that resolves the incident.

  • Save test_flight_recorder.py.
  • Run the expanded suite by executing:
python -m pytest

You should see 2 passed in the test summary. The suite now protects both the recovery set and the repaired refund decision.

Refund routing test failed?

  • Confirm that the scenario name is refund_route.
  • Confirm that the test searches for the route_issue operation.
  • Check that the assertion reads selected_tool from the span attributes.

Ask for help with comparing the repaired route span.

  • Place the failure-evidence test at the end of test_flight_recorder.py by pasting:
def test_failure_probe_stays_diagnosable(tmp_path):
    # Preserve error evidence while successful routes remain repaired.
    trace_path = tmp_path / "timeout.jsonl"
    recorder = FlightRecorder(trace_path)
    result = run_agent("timeout_probe", recorder, repaired=True)
    recorder.close()
    spans = read_spans(trace_path)
    tool_span = next(span for span in spans if span["operation"] == "call_tool")
    assert result["status"] == "error"
    assert tool_span["status"] == "ERROR"
    assert tool_span["error_type"] == "ToolTimeout"

Why keep a failing probe?

Observability must explain failures instead of hiding them. This test confirms that a simulated timeout still records the failing operation, error status, and error type.

  • Save test_flight_recorder.py.
  • Run the complete regression suite by executing:
python -m pytest

You should see 3 passed in the test summary. That result protects four repaired scenarios plus the error evidence needed for diagnosis.

Failure-evidence test failed?

  • Confirm that the probe scenario is timeout_probe.
  • Check that the test reads the call_tool span.
  • Confirm that the expected error type is ToolTimeout.

Ask for help with debugging the failure-evidence assertion.

✔️ Awesome, I've got everything!

Your suite passes three tests and protects the repaired route plus its diagnostic evidence. Double check that test_flight_recorder.py is saved.

ⓧ I'd like to double check the full code

Compare your test_flight_recorder.py with this complete version.

from flight_recorder import FlightRecorder, RECOVERY_SCENARIOS, read_spans, run_agent


def test_repaired_recovery_scenarios(tmp_path):
    # Isolate each repaired run in its own temporary trace file.
    for scenario_name in RECOVERY_SCENARIOS:
        trace_path = tmp_path / f"{scenario_name}.jsonl"
        recorder = FlightRecorder(trace_path)
        result = run_agent(scenario_name, recorder, repaired=True)
        recorder.close()
        spans = read_spans(trace_path)
        operations = {span["operation"] for span in spans}
        assert result["status"] == "success"
        assert {"agent.run", "route_issue", "call_tool", "compose_recommendation"} <= operations


def test_refund_uses_billing_lookup(tmp_path):
    # Capture the route decision that fixes the original incident.
    trace_path = tmp_path / "refund.jsonl"
    recorder = FlightRecorder(trace_path)
    result = run_agent("refund_route", recorder, repaired=True)
    recorder.close()
    spans = read_spans(trace_path)
    route_span = next(span for span in spans if span["operation"] == "route_issue")
    assert result["status"] == "success"
    assert route_span["attributes"]["selected_tool"] == "billing_lookup"


def test_failure_probe_stays_diagnosable(tmp_path):
    # Preserve error evidence while successful routes remain repaired.
    trace_path = tmp_path / "timeout.jsonl"
    recorder = FlightRecorder(trace_path)
    result = run_agent("timeout_probe", recorder, repaired=True)
    recorder.close()
    spans = read_spans(trace_path)
    tool_span = next(span for span in spans if span["operation"] == "call_tool")
    assert result["status"] == "error"
    assert tool_span["status"] == "ERROR"
    assert tool_span["error_type"] == "ToolTimeout"
Write the observability report

The final report turns test output and trace fields into a reviewable engineering result. It separates fixed simulation data from local wall measurements so readers know which numbers should match across machines.

  • Click the Explorer icon in the left sidebar.
  • Click the New File icon beside ai-agent-flight-recorder.
  • Enter observability_report.md.
  • Press Enter.
  • Create the report by pasting this content:
# Observability Report

## Incident

The refund scenario selected `knowledge_search` and failed in `call_tool` with `IncorrectRoute`.

## Repair

The repaired mapping selects `billing_lookup` for the refund category.
The repaired refund trace completes `route_issue`, `retrieve_context`, `call_tool`, and `compose_recommendation` with `OK` status.

## Regression proof

- All four recovery scenarios return `success` with repaired routing.
- The refund route records `selected_tool=billing_lookup`.
- The timeout probe remains diagnosable as `call_tool`, `ERROR`, and `ToolTimeout`.
- The complete pytest suite reports three passing tests.

## Deterministic simulated latency

| Scenario | Total simulated latency |
| --- | ---: |
| warranty_question | 34 ms |
| password_reset | 35 ms |
| refund_route | 37 ms |
| shipping_delay | 40 ms |

Nearest-rank p95 uses rank `ceil(0.95 * 4) = 4`, so simulated p95 is **40 ms**.

## Local wall timing

`wall_duration_ms` measures local execution and varies by machine. `simulated_latency_ms` is the stable value for regression comparisons.

How does the report prove improvement?

  • The incident section preserves the original failing decision and error.
  • The repair section names the changed route and successful operation sequence.
  • The regression section ties the conclusion to executable tests.
  • The latency section reports nearest-rank p95 over the four fixed recovery cases.
  • Save observability_report.md.
  • Confirm that the report exists in the project folder by running:
ls observability_report.md

You should see observability_report.md in the output. The report now sits beside the code and regression suite it describes.

Report file not found?

  • Confirm that the terminal path ends with ai-agent-flight-recorder.
  • Check that the filename uses the .md extension.
  • Save the open report before running the file check again.

Ask for help with locating the observability report.

Before you reopen the timeline, do you expect the repaired refund trace to contain any red error row?

  • Start the local timeline server by running:
fastapi dev viewer.py
  • Open http://127.0.0.1:8000 in your browser.
  • Find the newest refund_route trace card.
  • Read the selected_tool attribute in the route_issue row.
  • Check the status of every operation in that card.

You should see selected_tool set to billing_lookup with OK across the repaired trace. The timeline, tests, and report now tell the same story.

That closes the observability loop: you found the bad route, repaired it, and protected the evidence with repeatable tests. Next, you will turn the finished build into a GitHub-ready README that explains its architecture and execution path.

Document the Flight Recorder

Your repaired route now has trace evidence and regression protection. The observability report also records the incident and its measurable outcome.

Now you will turn that work into a GitHub-ready README.md. You will use VS Code's built-in Markdown preview to check how the finished document renders.

In this step, get ready to:
  • Replace the starter README with an accurate project overview.
  • Document the architecture, repository layout, setup, and execution commands.
  • Preview the rendered README and confirm that it represents the finished project.
Write the overview and architecture

A repository visitor needs the purpose and design before the commands. This opening explains the failure the project solves and the evidence it captures.

  • Select README.md in the Explorer sidebar.
  • Replace the starter note with this first README section:
# AI Agent Flight Recorder

A local tracing and telemetry harness for isolating, recording, and diagnosing failures in AI agent routing workflows.

## Architecture and Design

This project uses a decoupled **local flight recorder** context manager. It wraps agent operations to capture telemetry without mixing tracing code into the routing logic or relying on an external APM platform.

- **Telemetry formatter:** Converts execution state into structured, correlated JSONL spans with parent-child relationships.
- **Latency separation:** Keeps deterministic `simulated_latency_ms` separate from machine-dependent `wall_duration_ms`.
- **FastAPI visualizer:** Renders raw JSONL spans as a parent-child timeline in the browser.
- **Regression proof:** Uses pytest to protect repaired routes and preserve diagnosable failures.
- **Optional retry extension:** Adds one bounded retry for a safe read-only timeout while retaining the failed attempt.

What does this section communicate?

  • The opening names the routing failure this project helps diagnose.
  • The architecture bullets connect correlated JSONL spans to the browser timeline.
  • The latency bullet separates deterministic simulation data from local wall timing.
  • The final bullets connect pytest regression proof to the optional retry extension.
  • Save README.md.
  • Press Cmd+Shift+V on macOS or Ctrl+Shift+V on Windows or Linux to open the Markdown preview.

You should see the project title followed by five architecture bullets. The inline field names should render as code.

Preview is blank or unformatted?

Confirm that the active editor tab is README.md and that the file is saved before reopening the preview.

If the headings still render as plain text, help me check my README Markdown.

Add the repository layout and setup

The next sections show readers what each file does and how to recreate the local environment. The trace file is marked as runtime output because .gitignore keeps it out of Git.

  • Place your cursor after the optional retry extension bullet.
  • Append the repository layout by pasting:


## Repository Layout

```text
├── flight_recorder.py       # Tracing context manager and agent runtime
├── retry_policy.py          # Retry decision boundary
├── viewer.py                # FastAPI timeline server
├── test_flight_recorder.py  # Core regression suite
├── tests/
│   └── test_secret_mission.py  # Optional retry extension tests
├── requirements.txt         # Pinned Python dependencies
├── observability_report.md  # Incident, repair, and latency evidence
├── README.md                # Project documentation
├── .gitignore               # Local-only exclusions
└── traces/
    └── agent.jsonl          # Generated local trace file
```

`traces/agent.jsonl` is created at runtime and excluded from Git by `.gitignore`.

Why mark the trace as generated?

The timeline needs traces/agent.jsonl while the project runs. Excluding it from Git keeps local execution evidence out of the repository history.

  • Save README.md.
  • Return to the open Markdown preview.

You should see a tree containing the runtime, viewer, tests, report, and generated trace path.

  • Return to the README.md editor tab.
  • Append the requirements and platform setup by pasting:


## Requirements

- Python 3.11 or newer.
- A terminal opened inside the project folder.

## Setup

### macOS or Linux

```bash
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
```

### Windows PowerShell

```powershell
py -3.11 -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install -r requirements.txt
```

Why include both setup paths?

The environment activation command differs between POSIX shells and Windows PowerShell. Both paths install the same pinned dependencies from requirements.txt.

  • Save README.md.
  • Return to the Markdown preview.

You should see separate setup sections for macOS or Linux and Windows PowerShell. Each command group should render in its own fenced block.

Repository tree swallowed the setup section?

A missing closing code fence makes every later section render inside the tree. Confirm that three backticks appear immediately after the agent.jsonl line.

If the setup headings still appear inside the tree, help me find the unclosed README code fence.

Document execution and lessons

The final README section gives readers a path from failure to repair. It also records the engineering lessons demonstrated by the trace evidence.

  • Return to the README.md editor tab.
  • Append the execution guide and lessons by pasting:


## Run the Project

### Reproduce and repair the refund route

```bash
python flight_recorder.py trace refund_route
python flight_recorder.py trace refund_route --repair
```

The first run records the incorrect route. The repaired run selects `billing_lookup` and completes successfully.

### Launch the timeline

```bash
fastapi dev viewer.py
```

Open `http://127.0.0.1:8000` to inspect the nested span timeline. Press `Ctrl+C` in the server terminal when you want to stop it.

### Run the tests

```bash
python -m pytest
```

The test summary should report that every collected test passed.

What does the execution guide prove?

  • The first two commands reproduce the incident and its repaired outcome.
  • The FastAPI command exposes the trace evidence in the browser.
  • The final command checks the project contracts with the regression suite.
  • Save README.md.
  • Return to the Markdown preview.

You should see three runnable sections with separate command blocks for tracing, the timeline, and tests.

  • Return to the README.md editor tab.
  • Complete the README with the optional extension and lessons learned:


## Optional Retry Extension

The Secret Mission adds one bounded retry for `knowledge_search` timeouts. Run the six-scenario demonstration with:

```bash
python flight_recorder.py secret --runs 6
```

Recovered traces retain the failed first attempt and the successful second attempt under the same parent span.

## Lessons Learned

- **Diagnosing opaque failures:** Correlated spans reveal the operation and route decision behind a generic error.
- **Separating telemetry clocks:** Deterministic simulated latency supports regression comparisons while wall duration reflects the local machine.
- **Testing observability:** Regression tests protect both successful behavior and the evidence needed to explain failures.
- **Bounding retries:** A retry policy must limit attempts, approve only safe operations, and preserve failed attempts for diagnosis.

Why label the retry as optional?

The core project is complete before the Secret Mission. This label keeps the README accurate whether a repository visitor reviews the core build or the bounded retry extension.

  • Save README.md.
  • Open the Markdown preview with Cmd+Shift+V on macOS or Ctrl+Shift+V on Windows or Linux.

You should see a complete document ending with four lessons learned. The repository layout, commands, and optional extension should each have their own section.

Final preview does not match?

Check that every part was pasted in order and that each fenced command block has both an opening and closing line of three backticks.

For a section-by-section comparison, help me validate the complete README.

✔️ Awesome, I've got everything!

Your rendered README explains the finished project from architecture through verification. Double check that README.md is saved.

ⓧ I'd like to double check the full code

Compare your README.md with this complete version.

# AI Agent Flight Recorder

A local tracing and telemetry harness for isolating, recording, and diagnosing failures in AI agent routing workflows.

## Architecture and Design

This project uses a decoupled **local flight recorder** context manager. It wraps agent operations to capture telemetry without mixing tracing code into the routing logic or relying on an external APM platform.

- **Telemetry formatter:** Converts execution state into structured, correlated JSONL spans with parent-child relationships.
- **Latency separation:** Keeps deterministic `simulated_latency_ms` separate from machine-dependent `wall_duration_ms`.
- **FastAPI visualizer:** Renders raw JSONL spans as a parent-child timeline in the browser.
- **Regression proof:** Uses pytest to protect repaired routes and preserve diagnosable failures.
- **Optional retry extension:** Adds one bounded retry for a safe read-only timeout while retaining the failed attempt.

## Repository Layout

```text
├── flight_recorder.py       # Tracing context manager and agent runtime
├── retry_policy.py          # Retry decision boundary
├── viewer.py                # FastAPI timeline server
├── test_flight_recorder.py  # Core regression suite
├── tests/
│   └── test_secret_mission.py  # Optional retry extension tests
├── requirements.txt         # Pinned Python dependencies
├── observability_report.md  # Incident, repair, and latency evidence
├── README.md                # Project documentation
├── .gitignore               # Local-only exclusions
└── traces/
    └── agent.jsonl          # Generated local trace file
```

`traces/agent.jsonl` is created at runtime and excluded from Git by `.gitignore`.

## Requirements

- Python 3.11 or newer.
- A terminal opened inside the project folder.

## Setup

### macOS or Linux

```bash
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
```

### Windows PowerShell

```powershell
py -3.11 -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install -r requirements.txt
```

## Run the Project

### Reproduce and repair the refund route

```bash
python flight_recorder.py trace refund_route
python flight_recorder.py trace refund_route --repair
```

The first run records the incorrect route. The repaired run selects `billing_lookup` and completes successfully.

### Launch the timeline

```bash
fastapi dev viewer.py
```

Open `http://127.0.0.1:8000` to inspect the nested span timeline. Press `Ctrl+C` in the server terminal when you want to stop it.

### Run the tests

```bash
python -m pytest
```

The test summary should report that every collected test passed.

## Optional Retry Extension

The Secret Mission adds one bounded retry for `knowledge_search` timeouts. Run the six-scenario demonstration with:

```bash
python flight_recorder.py secret --runs 6
```

Recovered traces retain the failed first attempt and the successful second attempt under the same parent span.

## Lessons Learned

- **Diagnosing opaque failures:** Correlated spans reveal the operation and route decision behind a generic error.
- **Separating telemetry clocks:** Deterministic simulated latency supports regression comparisons while wall duration reflects the local machine.
- **Testing observability:** Regression tests protect both successful behavior and the evidence needed to explain failures.
- **Bounding retries:** A retry policy must limit attempts, approve only safe operations, and preserve failed attempts for diagnosis.

Your project now ends with documentation that matches the code, commands, and evidence a reviewer can inspect. The finished README is ready to accompany the repository.

Secret mission

Recover the Every-Third-Run Timeout

A timeout strikes every third retry-safe lookup. Use trace evidence to uncover the pattern, recover with one bounded retry, and preserve the failed attempt for diagnosis.

Clean Up Your Resources

Clean Up Your Resources

All execution stays on your machine. This project has no ongoing service costs.

Choose whether to leave the timeline running. You can stop it for later or remove the local project contents.

Resources you used:

  • The local FastAPI development process that serves the timeline at http://127.0.0.1:8000.
  • The .venv virtual environment that holds the pinned project dependencies.
  • The project repository open in VS Code. It contains your source code plus all generated evidence.

Keep everything running

Leave everything as it is while you inspect the trace timeline or extend the retry policy.

  • Leave the FastAPI process running so the timeline stays available at http://127.0.0.1:8000.
  • Keep the project artifacts in the open repository.
  • Keep .venv so the pinned dependencies remain available.

Pause - I'll come back to this later

Free port 8000 by ending the local timeline process. Your trace evidence and virtual environment stay ready for your return.

  • Switch back to the terminal panel where the FastAPI timeline process is running.
  • Press Ctrl+C to stop the process.
  • Return to the existing timeline browser tab.
  • Refresh the browser tab to confirm the local timeline no longer responds.

The terminal prompt returns after the process stops. Every project file remains in the repository.

Delete - I don't want to use this again

Remove the running process and every visible repository item when you want a clean local reset. Deletion is permanent for uncommitted local evidence.

  • Switch back to the terminal panel where the FastAPI timeline process is running.
  • Press Ctrl+C to stop the process.
  • Return to the Explorer sidebar in VS Code.
  • Select every top-level file and folder shown for the repository.
  • Right-click the selected items.
  • Choose Delete from the context menu.
  • Confirm the deletion when VS Code asks.
  • Confirm the Explorer sidebar no longer lists the project files or .venv.

Your machine is clear of the local flight recorder. No cloud resources or paid services remain.

Nice Work!

Nice Work!

Outstanding work! You transformed an opaque simulated support agent into a workflow whose failures can be reconstructed from correlated JSONL evidence.

You've learned how to:

  • Capture a complete agent execution as correlated spans with parent-child relationships. The resulting trace preserves execution hierarchy. It also preserves the diagnostic evidence required to reconstruct a failure.
  • Use a local FastAPI timeline to group operations by trace ID. Diagnose the incorrect refund route from call_tool failure evidence. Repair the selected operation to billing_lookup.
  • Protect the trace contract with deterministic pytest regression tests. Quantify the before-and-after improvement in observability-report.md.
  • Secret Mission: Apply a bounded retry to every-third-run ToolTimeout failures from the read-only knowledge_search operation. Preserve the failed first attempt under its original trace. Reject retries for unsafe operations.

Ready to quiz yourself?