heart-scalpel 6d7b94c5f8
refactor(middlewares): declarative layered builder; pin chain order with tests (#3809)
Split `_build_runtime_middlewares`'s flat list into three named declarative
sublists (outer_wrappers / thread_hooks / tail) and drop the
`middlewares.insert(2, UploadsMiddleware())` magic-index pattern. The
declarative structure makes the layering self-documenting and immune to
position drift when the head of the list changes.

Move UploadsMiddleware to run after ThreadDataMiddleware in the chain.
Under the previous order (a magic-index artifact introduced when #3662
prepended InputSanitizationMiddleware), UploadsMiddleware scanned the
uploads directory before ThreadDataMiddleware created it under
lazy_init=False, so historical files could be missed on the first run of
a thread. Narrow path — the upload endpoint normally pre-creates the
directory — but the order is the correct semantic and is now locked.

Documentation:
- backend/AGENTS.md middleware chain renumbered: ThreadDataMiddleware is
  now #3, UploadsMiddleware #4 (was reversed).

Tests (backend/tests/test_tool_error_handling_middleware.py):
- test_build_lead_runtime_middlewares_orders_thread_data_before_uploads
  — focused td_idx < um_idx assertion.
- test_build_lead_runtime_middlewares_chain_order_matches_agents_md
  — full-chain order pin using real classes, so a swap between any pair
    is caught (the existing FakeMiddleware-stubbed tests cannot detect
    this).
- test_lead_runtime_chain_finds_historical_uploads_under_lazy_init_false
  — integration anchor: under lazy_init=False, ThreadDataMiddleware
    creates the dirs, then UploadsMiddleware surfaces a pre-existing
    historical file in the injected <uploaded_files> context.
2026-06-28 23:29:02 +08:00
..