diff --git a/ROADMAP.md b/ROADMAP.md
index 646921ece..9653f3376 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,6 +44,8 @@ graph LR
tpa_db["tpa-db: versioned TPA signature databas…"]
remote_access_tunnel["Remote access tunnel (feature-flagged M…"]
schema_deferred["Deferred-schema serialization for the d…"]
+ agent_scope_hardening["Agent-token scope hardening: every MCP…"]
+ auto_routing_mode["Auto routing mode: budget-fitted tool s…"]
token_bench["Token-efficiency benchmark: measured sa…"]
tool_graph["Tool co-occurrence graph (experimental,…"]
telemetry_identity["Telemetry identity & data quality (mach…"]
@@ -57,6 +59,10 @@ graph LR
tpa_db --> remote_access_tunnel
ux_audit --> remote_access_tunnel
analytics_dashboard --> remote_access_tunnel
+ schema_deferred --> agent_scope_hardening
+ agent_scope_hardening --> auto_routing_mode
+ schema_deferred --> auto_routing_mode
+ token_bench --> auto_routing_mode
schema_deferred --> token_bench
analytics_dashboard --> tool_graph
telemetry_identity --> telemetry_v7_churn
@@ -65,8 +71,8 @@ graph LR
classDef in_progress fill:#1f6feb,stroke:#0b3d91,color:#ffffff;
classDef todo fill:#6e7781,stroke:#3d4248,color:#ffffff;
class sandbox_isolation,scanner_v2,analytics_dashboard,scanner_simplification,schema_deferred done;
- class ux_audit,action_log_transparency,token_bench,telemetry_identity,telemetry_v7_churn in_progress;
- class tpa_db,remote_access_tunnel,tool_graph todo;
+ class ux_audit,action_log_transparency,agent_scope_hardening,token_bench,telemetry_identity,telemetry_v7_churn in_progress;
+ class tpa_db,remote_access_tunnel,auto_routing_mode,tool_graph todo;
```
**Independent epics** (15) — no cross-epic prerequisites; each stands alone:
@@ -184,10 +190,8 @@ graph LR
action_log_glance_view --> action_log_retention_tie_in
classDef done fill:#1f7a1f,stroke:#0d3d0d,color:#ffffff;
- classDef in_progress fill:#1f6feb,stroke:#0b3d91,color:#ffffff;
classDef todo fill:#6e7781,stroke:#3d4248,color:#ffffff;
- class sessions_web_ui done;
- class activity_storage_bounds in_progress;
+ class sessions_web_ui,activity_storage_bounds done;
class action_log_glance_view,action_log_tray_menu,tray_menu_open_telemetry,action_log_retention_tie_in todo;
```
@@ -198,7 +202,64 @@ graph LR
| Activity in the tray menu (recent tool calls + security events, jump to full log) | ⚪ Todo | — |
| tray_menu_opened counter: Swift menuWillOpen (MCPProxyApp.swift:192) -> lightweight POST /api/v1/telemetry/tray-menu-opened -> registry counter -> heartbeat tray_menu_opened_24h | ⚪ Todo | — |
| Tie activity retention/size into the glance view | ⚪ Todo | — |
-| Bound every activity-adjacent store: response truncation on the write path (#1173/#1174), per-server tool_calls buckets (#1176), omitempty zero-erasure (#1175) | 🔵 In progress | #1174 |
+| Bound every activity-adjacent store: response truncation on the write path (#1173/#1174), per-server tool_calls buckets (#1176), omitempty zero-erasure (#1175) | 🟢 Done | #1174 #1214 |
+
+
+
+
+🔵 Agent-token scope hardening: every MCP request authorized by its own scope (spec 105) — In progress · P1
+
+> The Spec 104 cross-model review verified 'an agent token sees and uses only its granted servers, profile and tiers' against the code one surface at a time and found eight places where a legitimately narrow token could learn about or act on servers outside its grant: cached responses, set_profile and profile-URL responses, retrieve_tools metadata, direct-publication filtering, target-tier execution, aggregated prompts, per-server management ops, and refusal shapes. Spec 105 is the acceptance contract (19 astra rounds, ready-for-plan 2026-09-07). Five fix sessions ran in parallel from the review and MERGED 2026-09-08 (#1223 target tier, #1224 tail_log, #1225 set_profile, #1226 read_cache provenance, #1227 prompt owner + deleted-pin enumeration), each live-verified against a baseline binary and astra-reviewed to CLEAN. Each of those PR bodies carries a 'Follow-ups / Spec 105 gaps' checklist — the todo tasks below are those lists grouped by FR. Prerequisite for auto-routing-mode: Spec 104 FR-016 states the invariant these corrections make true.
+
+Spec: [105-agent-scope-hardening](./specs/105-agent-scope-hardening/)
+
+```mermaid
+graph LR
+ scope_fix_target_tier["FR-009 (dispatch half): call_tool_* requires…"]
+ scope_fix_tail_log["FR-007 (name half): upstream_servers tail_log…"]
+ scope_fix_set_profile["FR-003: set_profile reports token ∩ profile,…"]
+ scope_fix_read_cache["FR-001: cached responses carry the producer's…"]
+ scope_fix_prompts_profile_url["FR-006 + FR-004 (deleted pin): aggregated pro…"]
+ scope_retrieve_tools["FR-005: retrieve_tools filters by scope BEFOR…"]
+ scope_direct_publication["FR-008: direct-surface definitions take owner…"]
+ scope_refusal_shapes["FR-010: scope-first refusal precedence; dispa…"]
+ scope_selectable_profile_predicate["FR-003/FR-004 remainder: selectable-profile p…"]
+ scope_cache_legacy_invalidation["FR-002 + FR-001 remainder: legacy/unstamped a…"]
+ scope_log_attribution["FR-007 remainder: per-record canonical log ow…"]
+ scope_target_identity_producers["FR-009 remainder: producer-side exact-name id…"]
+ scope_regression_suite["FR-011/FR-013/FR-014: two-fixture differentia…"]
+
+ scope_retrieve_tools --> scope_refusal_shapes
+ scope_fix_set_profile --> scope_selectable_profile_predicate
+ scope_fix_prompts_profile_url --> scope_selectable_profile_predicate
+ scope_fix_read_cache --> scope_cache_legacy_invalidation
+ scope_fix_tail_log --> scope_log_attribution
+ scope_fix_target_tier --> scope_target_identity_producers
+ scope_retrieve_tools --> scope_regression_suite
+ scope_direct_publication --> scope_regression_suite
+ scope_refusal_shapes --> scope_regression_suite
+
+ classDef done fill:#1f7a1f,stroke:#0d3d0d,color:#ffffff;
+ classDef todo fill:#6e7781,stroke:#3d4248,color:#ffffff;
+ class scope_fix_target_tier,scope_fix_tail_log,scope_fix_set_profile,scope_fix_read_cache,scope_fix_prompts_profile_url done;
+ class scope_retrieve_tools,scope_direct_publication,scope_refusal_shapes,scope_selectable_profile_predicate,scope_cache_legacy_invalidation,scope_log_attribution,scope_target_identity_producers,scope_regression_suite todo;
+```
+
+| Task | Status | Refs |
+| --- | --- | --- |
+| FR-009 (dispatch half): call_tool_* requires the TARGET tool's tier, fail closed on unresolved tiers; approval records keep exact ns:name identity | 🟢 Done | #1223 |
+| FR-007 (name half): upstream_servers tail_log authorizes the server against effective scope before lookup, non-disclosing | 🟢 Done | #1224 |
+| FR-003: set_profile reports token ∩ profile, selectable-profile predicate, non-selectable == nonexistent | 🟢 Done | #1225 |
+| FR-001: cached responses carry the producer's authorization snapshot; read_cache and the REST cache branch refuse narrower readers | 🟢 Done | #1226 |
+| FR-006 + FR-004 (deleted pin): aggregated prompts authorized by canonical registration owner; profile URL / set_profile stop enumerating on a deleted pin | 🟢 Done | #1227 |
+| FR-005: retrieve_tools filters by scope BEFORE limiting; indexed counts, usage ranking, debug output and session risk computed over the authorized population only | ⚪ Todo | — |
+| FR-008: direct-surface definitions take owner and tier from their own registration identity at every publication seam, both skew directions, full and deferred | ⚪ Todo | — |
+| FR-010: scope-first refusal precedence; dispatch denials and 'available servers' never name hidden servers; describe_tool not-found and alias resolution computed over the authorized corpus | ⚪ Todo | — |
+| FR-003/FR-004 remainder: selectable-profile predicate for UNPINNED tokens on /mcp/p/, /mcp/p, /mcp/p/ and set_profile; identical status+body across missing / deleted / not-selectable / pin-mismatch / no-profiles (#1225 + #1227 follow-up lists) | ⚪ Todo | — |
+| FR-002 + FR-001 remainder: legacy/unstamped and internal (registry, guesser) cache entries refused for every caller and durably invalidated; monotone recursive provenance; existence-non-disclosing refusal on MCP and REST (#1226 follow-up list) | ⚪ Todo | — |
+| FR-007 remainder: per-record canonical log ownership (a/b vs a_b share one file), filter-before-limit + authorized lines_returned, subject-bound OAuth-callback logging, canonical container ownership in Docker cleanup (#1224 follow-up list) | ⚪ Todo | — |
+| FR-009 remainder: producer-side exact-name identity (checkToolApprovals / differential index collapse ns:erase to erase), direct-name dispatch + preflight share lookupToolApproval, unresolved/stale identity refuses scoped callers, full 54-cell acceptance tables (#1223 follow-up list) | ⚪ Todo | — |
+| FR-011/FR-013/FR-014: two-fixture differential oracle with sentinels across the applicability matrix, credential-authenticated HTTP matrix over every /mcp surface, admin p95 perf gate on the frozen 527-tool snapshot | ⚪ Todo | — |
@@ -394,6 +455,31 @@ graph LR
+
+⚪ Auto routing mode: budget-fitted tool surface per session (spec 104) — Todo · P1
+
+> routing_mode: auto measures, per session and on the catalog that session will actually see, the three candidate surfaces (direct full, direct deferred, retrieve compact — the Spec 103 bench cell names) with the real tokenizer and serves the richest rung under a 12,000-token budget, so the small-fleet developer gets the whole menu with schemas and the 1,000-tool fleet stays on search — the current default is strictly worse than no proxy for the first population. Decision record (rung, three measurements, budget, counts, scope label, reason, time) surfaces in the routing API, doctor, tray, Web UI and telemetry; hysteresis so a 1% catalog change never flips a live session. Spec: 14 astra rounds, ready-for-plan 2026-09-07; its fixed-surface corrections were split out as Spec 105 (FR-016 states the invariant 105 makes true), hence the hard dependency. P1 = US1-4 (rung selection, session stability, scoped measurement, routing API + doctor); P2 = US5-6 (hysteresis reporting, tray/Web UI rendering, telemetry).
+
+Spec: [104-auto-routing-mode](./specs/104-auto-routing-mode/)
+
+```mermaid
+graph LR
+ auto_routing_p1["P1 (US1-4): per-session measurement of the th…"]
+ auto_routing_p2["P2 (US5-6): hysteresis reporting on catalog c…"]
+
+ auto_routing_p1 --> auto_routing_p2
+
+ classDef todo fill:#6e7781,stroke:#3d4248,color:#ffffff;
+ class auto_routing_p1,auto_routing_p2 todo;
+```
+
+| Task | Status | Refs |
+| --- | --- | --- |
+| P1 (US1-4): per-session measurement of the three candidates on the scoped catalog, rung selection under the budget, stable sessions, decision record in routing API + doctor | ⚪ Todo | — |
+| P2 (US5-6): hysteresis reporting on catalog change, tray + Web UI rendering of the decision, telemetry counters | ⚪ Todo | — |
+
+
+
⚪ Windows native tray app — Todo · P2 · MCP-43
@@ -776,6 +862,7 @@ graph LR
| Web UI + macOS app UX audit | In progress | P0 | — | | |
| Release qualification gate (auto-QA matrix blocks the tag) | In progress | P0 | — | [081-release-qa-gate](./specs/081-release-qa-gate/) | |
| Action log / transparency — info at a glance | In progress | P1 | — | | |
+| Agent-token scope hardening: every MCP request authorized by its own scope (spec 105) | In progress | P1 | — | [105-agent-scope-hardening](./specs/105-agent-scope-hardening/) | |
| Token-efficiency benchmark: measured savings, published results | In progress | P1 | 62/64 (97%) | [103-token-bench](./specs/103-token-bench/) | |
| Telemetry identity & data quality (machine_id + CI-filter hardening) | In progress | P1 | — | | |
| Telemetry v7: honest funnel + churn instrumentation | In progress | P1 | — | [080-telemetry-v7-churn](./specs/080-telemetry-v7-churn/) | |
@@ -783,6 +870,7 @@ graph LR
| Planning/docs truth automation | In progress | P2 | — | | |
| Discovery-quality eval harness (Spec 065 second half) | In progress | P3 | — | [065-evaluation-foundation](./specs/065-evaluation-foundation/) | |
| tpa-db: versioned TPA signature database for the offline scanner | Todo | P1 | — | [101-tpa-db](./specs/101-tpa-db/) | |
+| Auto routing mode: budget-fitted tool surface per session (spec 104) | Todo | P1 | — | [104-auto-routing-mode](./specs/104-auto-routing-mode/) | |
| Windows native tray app `MCP-43` | Todo | P2 | — | | |
| Remote access tunnel (feature-flagged MVP, spec 089) | Todo | P2 | — | [089-remote-access-tunnel](./specs/089-remote-access-tunnel/) | |
| Tool co-occurrence graph (experimental, feature-flagged) | Todo | P2 | — | | |
@@ -919,3 +1007,5 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—`
| [101-tpa-db](./specs/101-tpa-db/) | — | — |
| [102-schema-deferred](./specs/102-schema-deferred/) | `shipped` | 89/89 (100%) |
| [103-token-bench](./specs/103-token-bench/) | `shipped` | 62/64 (97%) |
+| [104-auto-routing-mode](./specs/104-auto-routing-mode/) | — | — |
+| [105-agent-scope-hardening](./specs/105-agent-scope-hardening/) | — | — |
diff --git a/roadmap.yaml b/roadmap.yaml
index e1d9930a8..d9c3b24ae 100644
--- a/roadmap.yaml
+++ b/roadmap.yaml
@@ -255,10 +255,10 @@ epics:
depends_on: [action-log-glance-view]
- id: activity-storage-bounds
title: "Bound every activity-adjacent store: response truncation on the write path (#1173/#1174), per-server tool_calls buckets (#1176), omitempty zero-erasure (#1175)"
- status: in_progress
+ status: done
priority: P1
- pr: "#1174"
- note: "User report 2026-09-02 (#1173): config.db reached 940MB; activity_max_response_size existed but was never read, and server__tool_calls buckets have no size, count or age bound at all (the other ~432MB). #1174 (external contributor, CI green) wires the 64KB cap; #1176 and #1175 are the follow-ons. Retention backend (073) prunes activity records only, not the per-server buckets."
+ pr: ["#1174", "#1214"]
+ note: "User report 2026-09-02 (#1173): config.db reached 940MB; activity_max_response_size existed but was never read, and server__tool_calls buckets have no size, count or age bound at all (the other ~432MB). #1174 (external contributor) wired the 64KB cap on the write path; #1214 bounded the per-server tool_calls buckets, stopped omitempty erasing configured zeros and added `mcpproxy db compact` (closed #1175/#1176, 2026-09-05). Retention backend (073) prunes activity records only, not the per-server buckets."
depends_on: []
- id: analytics-dashboard
@@ -394,6 +394,99 @@ epics:
depends_on: []
note: "Direct mode enumerates every upstream tool but always ships full inputSchema (~30K tokens for a 100-tool fleet; Spec 083 profiling put ~77% of the payload in schemas agents rarely read). Deferred serialization keeps every tool name, description and annotation and appends the Spec 085 compact signature instead of the schema, with describe_tool on the direct surface to recover it and the shipped pre-dispatch validation turning a wrong guess into one self-healing retry. Not a new routing_mode — a serialization mode of the direct surface, on the same tool_response_mode axis that already governs retrieve_tools. Spec merged in #1035 (issue #971, maintainer-accepted direction). COMPLETE: all 89 tasks shipped in #1063; the settings UI for both serialization axes followed in #1082; #1083/#1084 fixed in #1086. MEASURED SAVINGS FELL WELL SHORT OF THE ~88% ORIGINALLY PROJECTED: 29.7% on the frozen 45-tool reference corpus and 34.8% on a 527-tool snapshot, with 38.9% the arithmetic ceiling even if both the schema and the signature were deleted. The projection assumed schemas dominate the payload; names, descriptions and annotations turn out to carry most of it. SC-001 was RESTATED per corpus shape (maintainer decision 2026-08-29): now >=25% on the 45-tool corpus and >=30% at fleet scale, both asserted in internal/server/mcp_routing_deferred_tokens_test.go, with the original 70% kept as an upper tripwire. Unblocks token-bench — and that measured shortfall is the first thing token-bench has to explain."
+ - id: agent-scope-hardening
+ title: "Agent-token scope hardening: every MCP request authorized by its own scope (spec 105)"
+ status: in_progress
+ priority: P1
+ spec: specs/105-agent-scope-hardening
+ depends_on: [schema-deferred]
+ note: "The Spec 104 cross-model review verified 'an agent token sees and uses only its granted servers, profile and tiers' against the code one surface at a time and found eight places where a legitimately narrow token could learn about or act on servers outside its grant: cached responses, set_profile and profile-URL responses, retrieve_tools metadata, direct-publication filtering, target-tier execution, aggregated prompts, per-server management ops, and refusal shapes. Spec 105 is the acceptance contract (19 astra rounds, ready-for-plan 2026-09-07). Five fix sessions ran in parallel from the review and MERGED 2026-09-08 (#1223 target tier, #1224 tail_log, #1225 set_profile, #1226 read_cache provenance, #1227 prompt owner + deleted-pin enumeration), each live-verified against a baseline binary and astra-reviewed to CLEAN. Each of those PR bodies carries a 'Follow-ups / Spec 105 gaps' checklist — the todo tasks below are those lists grouped by FR. Prerequisite for auto-routing-mode: Spec 104 FR-016 states the invariant these corrections make true."
+ tasks:
+ - id: scope-fix-target-tier
+ title: "FR-009 (dispatch half): call_tool_* requires the TARGET tool's tier, fail closed on unresolved tiers; approval records keep exact ns:name identity"
+ status: done
+ pr: "#1223"
+ depends_on: []
+ - id: scope-fix-tail-log
+ title: "FR-007 (name half): upstream_servers tail_log authorizes the server against effective scope before lookup, non-disclosing"
+ status: done
+ pr: "#1224"
+ depends_on: []
+ - id: scope-fix-set-profile
+ title: "FR-003: set_profile reports token ∩ profile, selectable-profile predicate, non-selectable == nonexistent"
+ status: done
+ pr: "#1225"
+ depends_on: []
+ - id: scope-fix-read-cache
+ title: "FR-001: cached responses carry the producer's authorization snapshot; read_cache and the REST cache branch refuse narrower readers"
+ status: done
+ pr: "#1226"
+ depends_on: []
+ - id: scope-fix-prompts-profile-url
+ title: "FR-006 + FR-004 (deleted pin): aggregated prompts authorized by canonical registration owner; profile URL / set_profile stop enumerating on a deleted pin"
+ status: done
+ pr: "#1227"
+ depends_on: []
+ - id: scope-retrieve-tools
+ title: "FR-005: retrieve_tools filters by scope BEFORE limiting; indexed counts, usage ranking, debug output and session risk computed over the authorized population only"
+ status: todo
+ priority: P1
+ depends_on: []
+ - id: scope-direct-publication
+ title: "FR-008: direct-surface definitions take owner and tier from their own registration identity at every publication seam, both skew directions, full and deferred"
+ status: todo
+ priority: P1
+ depends_on: []
+ - id: scope-refusal-shapes
+ title: "FR-010: scope-first refusal precedence; dispatch denials and 'available servers' never name hidden servers; describe_tool not-found and alias resolution computed over the authorized corpus"
+ status: todo
+ priority: P1
+ depends_on: [scope-retrieve-tools]
+ - id: scope-selectable-profile-predicate
+ title: "FR-003/FR-004 remainder: selectable-profile predicate for UNPINNED tokens on /mcp/p/, /mcp/p, /mcp/p/ and set_profile; identical status+body across missing / deleted / not-selectable / pin-mismatch / no-profiles (#1225 + #1227 follow-up lists)"
+ status: todo
+ priority: P1
+ depends_on: [scope-fix-set-profile, scope-fix-prompts-profile-url]
+ - id: scope-cache-legacy-invalidation
+ title: "FR-002 + FR-001 remainder: legacy/unstamped and internal (registry, guesser) cache entries refused for every caller and durably invalidated; monotone recursive provenance; existence-non-disclosing refusal on MCP and REST (#1226 follow-up list)"
+ status: todo
+ priority: P2
+ depends_on: [scope-fix-read-cache]
+ - id: scope-log-attribution
+ title: "FR-007 remainder: per-record canonical log ownership (a/b vs a_b share one file), filter-before-limit + authorized lines_returned, subject-bound OAuth-callback logging, canonical container ownership in Docker cleanup (#1224 follow-up list)"
+ status: todo
+ priority: P2
+ depends_on: [scope-fix-tail-log]
+ - id: scope-target-identity-producers
+ title: "FR-009 remainder: producer-side exact-name identity (checkToolApprovals / differential index collapse ns:erase to erase), direct-name dispatch + preflight share lookupToolApproval, unresolved/stale identity refuses scoped callers, full 54-cell acceptance tables (#1223 follow-up list)"
+ status: todo
+ priority: P2
+ depends_on: [scope-fix-target-tier]
+ - id: scope-regression-suite
+ title: "FR-011/FR-013/FR-014: two-fixture differential oracle with sentinels across the applicability matrix, credential-authenticated HTTP matrix over every /mcp surface, admin p95 perf gate on the frozen 527-tool snapshot"
+ status: todo
+ priority: P2
+ depends_on: [scope-retrieve-tools, scope-direct-publication, scope-refusal-shapes]
+
+ - id: auto-routing-mode
+ title: "Auto routing mode: budget-fitted tool surface per session (spec 104)"
+ status: todo
+ priority: P1
+ spec: specs/104-auto-routing-mode
+ depends_on: [agent-scope-hardening, schema-deferred, token-bench]
+ note: "routing_mode: auto measures, per session and on the catalog that session will actually see, the three candidate surfaces (direct full, direct deferred, retrieve compact — the Spec 103 bench cell names) with the real tokenizer and serves the richest rung under a 12,000-token budget, so the small-fleet developer gets the whole menu with schemas and the 1,000-tool fleet stays on search — the current default is strictly worse than no proxy for the first population. Decision record (rung, three measurements, budget, counts, scope label, reason, time) surfaces in the routing API, doctor, tray, Web UI and telemetry; hysteresis so a 1% catalog change never flips a live session. Spec: 14 astra rounds, ready-for-plan 2026-09-07; its fixed-surface corrections were split out as Spec 105 (FR-016 states the invariant 105 makes true), hence the hard dependency. P1 = US1-4 (rung selection, session stability, scoped measurement, routing API + doctor); P2 = US5-6 (hysteresis reporting, tray/Web UI rendering, telemetry)."
+ tasks:
+ - id: auto-routing-p1
+ title: "P1 (US1-4): per-session measurement of the three candidates on the scoped catalog, rung selection under the budget, stable sessions, decision record in routing API + doctor"
+ status: todo
+ priority: P1
+ depends_on: []
+ - id: auto-routing-p2
+ title: "P2 (US5-6): hysteresis reporting on catalog change, tray + Web UI rendering of the decision, telemetry counters"
+ status: todo
+ priority: P2
+ depends_on: [auto-routing-p1]
+
- id: token-bench
title: "Token-efficiency benchmark: measured savings, published results"
status: in_progress
diff --git a/specs/104-auto-routing-mode/checklists/requirements.md b/specs/104-auto-routing-mode/checklists/requirements.md
new file mode 100644
index 000000000..b3b31e3e3
--- /dev/null
+++ b/specs/104-auto-routing-mode/checklists/requirements.md
@@ -0,0 +1,63 @@
+# Specification Quality Checklist: Auto Routing Mode
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-09-07
+**Feature**: [spec.md](../spec.md)
+
+## Content Quality
+
+- [x] No implementation details (languages, frameworks, APIs) — existing mcpproxy concepts (rungs, endpoints, `describe_tool`, `doctor`) are named; no packages, types or library calls
+- [x] Focused on user value and business needs
+- [x] Written for non-technical stakeholders
+- [x] All mandatory sections completed
+
+## Requirement Completeness
+
+- [x] No [NEEDS CLARIFICATION] markers remain (the default-flip threshold is deferred to a follow-up spec under Assumptions)
+- [x] Requirements are testable and unambiguous
+- [x] Success criteria are measurable
+- [x] Success criteria are technology-agnostic (no implementation details)
+- [x] All acceptance scenarios are defined
+- [x] Edge cases are identified (settled catalog, tokenizer unavailable, session identity, serialization settings, scope edits, reload churn, who may read records, stdio)
+- [x] Scope is clearly bounded (Scope Boundary + Out of Scope)
+- [x] Dependencies and assumptions identified
+
+## Feature Readiness
+
+- [x] All functional requirements have clear acceptance criteria
+- [x] User scenarios cover primary flows
+- [x] Feature meets measurable outcomes defined in Success Criteria
+- [x] No implementation details leak into specification
+
+## Notes
+
+- Validation pass 1 (2026-09-07): all items pass on the first draft.
+- Cross-model review round 1 (opencode `github-copilot/gpt-6-astra`, 2026-09-07): verdict *fix-then-plan*, 24 findings (2 blockers). All applied in the same day:
+ - Blockers: agent-token callers now see only their own-scope verdict and never the unscoped one (FR-018, FR-021 projection matrix); session endpoints stay administrator-only. Measurement identity now includes caller kind and permission tiers, not just profile/servers (Definitions, FR-008, FR-030).
+ - Majors: cross-session test rewritten to "its own request scope" (US4); `set_profile` limited to the retrieve rung; "catalog generation" replaced by a measurement revision covering every visibility and rendering input; fallback verdicts made transient with recovery rules; tokenizer availability contract stated (configured-off vs init failure); measured object defined; SC-002 restricted to successful verdicts; ladder is a preference order; hysteresis transition table added (FR-007); settlement defined per server; parity defined against fixed endpoints in the corresponding serialization with listing-affecting settings enumerated; instruction composition rule (FR-019); legacy aliases follow `/mcp`; missing/unknown session handled by transport validation, no accepted no-session path; retention bounds split (FR-017); projection matrix (FR-021); SC-008 permits the caller's own profile slug locally; telemetry event unit defined (FR-026); release shape restated so authorization ships in P1.
+ - Minors: FR-012 named as the one compatibility exception to FR-004; CLI state table (FR-022); validation matrix (FR-002); benchmark conditions (SC-004); reproducible baseline (FR-024); mechanism prescriptions removed where possible (the Commit Message Conventions section is mandated by the repo template and stays); tokenizer wording corrected.
+- Validation pass 2 (2026-09-07): all checklist items still pass; zero clarification markers.
+- Cross-model review round 2 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 15 findings (1 blocker). All applied:
+ - Blocker: `read_cache` serves cached responses without checking the requesting credential — now prerequisite correction FR-016a (all surfaces) and a standalone bug task.
+ - Majors: `set_profile` response disclosure → FR-016b (all surfaces) and a standalone bug task; settlement made per scope; live-session idle expiry (30 min) defined separately from persisted-row cleanup; `disable_management`/`read_only_mode` declared startup-pinned; discovery-vs-execution asymmetry preserved and stated (read-only token case has one expected result); exact hysteresis comparisons and the skipped-lower-rung case stated; no-decision states per projection (`no_session_evaluated`, `no_current_authorized_verdict`); FR-022 state table with exit codes and a daemon-discovery correction; effective budget under an environment override; invalid-local-config-with-live-daemon state; telemetry typed domains and bucket enums; in-flight loss window accepted, SC-012 restricted to quiescent snapshots; release shape: every FR/SC required before public enablement.
+- Validation pass 3 (2026-09-07): all checklist items pass; zero clarification markers.
+- Cross-model review round 3 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 5 majors. All applied: FR-016c scopes `retrieve_tools` response metadata (usage stats, debug counts, session risk) to the caller's population; FR-016a fails closed on pre-feature cache entries with an upgrade fixture; FR-004 exceptions extended (management/read-only restart gating, all-modes live-session expiry) and `status` keeps exit 0 on no daemon; `no_unscoped_verdict` state distinguished from `no_session_evaluated` with the CLI reading the administrator routing projection; idle telemetry windows retain the budget and latest-measurement buckets.
+- Validation pass 4 (2026-09-07): all checklist items pass; zero clarification markers.
+- Cross-model review round 4 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 findings, both applied: `budget_below_all` now applies hysteresis eligibility first (a previously eligible direct candidate inside its band is still served) with an all-over-budget fixture; the auto floor's default instructions mention management tools only when they are listed for that session, tested under `disable_management` and `read_only_mode`.
+- Validation pass 5 (2026-09-07): all checklist items pass; zero clarification markers.
+- Cross-model review round 5 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 5 findings (1 high), all applied: per-recipient notification eligibility on the auto endpoint so out-of-scope fleet changes are never signalled (FR-012, FR-029); hysteresis-history expiry invalidates the cached decision, verdicts do not outlive history, clock-controlled reconnect test (FR-008); nested script calls follow the code-execution contract and `/mcp/all` parity is scoped to direct-name dispatch, collision fixture; settlement deadline anchored to admission with retries not extending it; listed vs discoverable count pairs defined per candidate (FR-020).
+- Validation pass 6 (2026-09-07): all checklist items pass; zero clarification markers.
+- Cross-model review round 6 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 5 findings (2 P1), all applied: FR-016d direct discovery filtered against its own publication's catalog with an origin-flip fixture; FR-016e notification recipient is the authenticated stream with A-POST/B-stream and narrowing tests; settlement checked before verdict reuse with a delayed-admission fixture (FR-008); cross-scope collision effects are notified as a stated exception with a fixture (FR-012); prior per-candidate eligibility recorded on every decision (FR-020).
+- Validation pass 7 (2026-09-07): all checklist items pass; zero clarification markers.
+- Cross-model review round 7 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 4 findings (1 high), all applied: FR-016f target-tier execution permission on retrieve dispatch regardless of the selected `call_tool_*` variant or intent-validation strictness (pre-existing gap, also filed as a standalone task); history-expiry tests re-specified as two seeded cases plus overlapping sessions (FR-008); "latest verdict" defined by binding order (FR-021); idle expiry: in-flight calls defer it, open streams do not, late completions cannot resurrect a session.
+- Validation pass 8 (2026-09-07): all checklist items pass; zero clarification markers.
+- Cross-model review round 8 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 findings, both pre-existing scope leaks, both applied: FR-016g aggregated prompts authorized against their canonical owner; FR-016b extended to profile-URL error responses. Filed as a standalone task.
+- Validation pass 9 (2026-09-07): all checklist items pass; zero clarification markers.
+- Cross-model review round 9 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 findings (1 high), both applied: FR-016h server-management operations (`tail_log`) authorized against token and profile scope before lookup (pre-existing leak, filed as a standalone task); FR-012/FR-016e recipient authorization extended to prompt-list notifications.
+- Validation pass 10 (2026-09-07): all checklist items pass; zero clarification markers.
+- Cross-model review round 10 (gpt-6-astra, 2026-09-07; the last under the 10-round cap in CLAUDE.md): verdict *fix-then-plan*, 2 medium definitional findings, both applied without a further re-review: telemetry "verdict decisions" unit defined as fresh decisions (cached-measurement re-decisions count, cached-verdict bindings do not) with the hysteresis counter on the same unit (FR-026, SC-012); `no_retained_verdict` state with a bounded historical last-bound record across API, CLI, UI and telemetry (FR-008, FR-021, FR-022).
+- **Status at cap**: 10 rounds run, 79 findings applied, last verdict *fix-then-plan* on two definitional items now fixed. Findings trend: 24 → 15 → 5 → 2 → 5 → 5 → 4 → 2 → 2 → 2; rounds 2–9 each surfaced pre-existing scope leaks in the fixed surfaces.
+- **Split (maintainer direction, 2026-09-07)**: the fixed-surface corrections FR-016a–d, f, g, h moved to [Spec 105](../../105-agent-scope-hardening/spec.md); this spec now depends on 105, keeps FR-016 (the invariant) and FR-016e (per-recipient notifications, auto-specific), and no longer lists the corrections as FR-004 exceptions. Cross-model review round 11 (user-authorized, post-split, 2026-09-07): verdict *fix-then-plan*, 2 medium, both applied: the historical last-bound record is retained per scope label independently of the 20-record rolling history, with a history-cap eviction fixture; telemetry excluded from the historical projection (measurement bucket `none` after expiry).
+- Cross-model review round 12 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 medium, both applied: FR-012's admission exception extended to prompt collisions and the global prompt cap with scoped fixtures; scope labels are a tagged category plus slug so a profile named `unscoped`/`token_scoped` never collides with the categories in records, projections or historical retention.
+- Cross-model review round 13 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 1 medium, applied: no-decision states are defined over sessions on auto-routed endpoints only, with a fixed-endpoint-only fixture (FR-021, FR-022).
+- Cross-model review round 14 (gpt-6-astra, 2026-09-07): **VERDICT: ready-for-plan.** No findings. Spec 104 is ready for `/speckit.plan`, contingent on Spec 105 (its prerequisite) reaching the same state.
diff --git a/specs/104-auto-routing-mode/spec.md b/specs/104-auto-routing-mode/spec.md
new file mode 100644
index 000000000..db99a865e
--- /dev/null
+++ b/specs/104-auto-routing-mode/spec.md
@@ -0,0 +1,365 @@
+# Feature Specification: Auto Routing Mode — Budget-Fitted Tool Surface Per Session
+
+**Feature Branch**: `104-auto-routing-mode`
+**Created**: 2026-09-07
+**Status**: Draft — cross-model review complete (14 rounds, gpt-6-astra, ready-for-plan 2026-09-07; fixed-surface corrections split into Spec 105)
+**Input**: User description: "Auto routing mode: routing_mode "auto" picks the tool surface per MCP session from a context token budget — direct/full, direct/deferred, or retrieve_tools+compact — using per-session tools, with the decision observable in API/doctor/tray/telemetry"
+
+**Related**: **Depends on Spec 105 (agent-token scope hardening)** — the fixed-surface corrections that make FR-016's invariant true. Spec 085 (compact router: `describe_tool`, compact signatures, pre-dispatch validation), Spec 102 (schema-deferred direct mode: the middle rung), Spec 103 (token-bench: the measurement vocabulary and mode-cell names reused here), Spec 031 (dedicated routing-mode endpoints), #971.
+
+## Context & Motivation
+
+A developer picks a routing mode once, by hand, and the fixed choice is wrong at both ends of the fleet-size scale. With ~20 tools the default `retrieve_tools` mode makes the agent search for tools it could simply have been shown, so every task starts with a discovery round trip that buys nothing. With ~1,000 tools `direct` mode ships a listing measured at 528,322 tokens on a real fleet — more than twice a 200k window — and deferral (Spec 102) brought the same fleet to 300,893 tokens: cheaper, still not loadable. In the band between, the right answer depends on the developer's context budget, and nothing today tells them which surface they are on or why.
+
+The three surfaces already exist. What is missing is the decision, and the developer's ability to see and trust it. `auto` makes the proxy measure the listing a session would actually receive, with the real tokenizer, and serve the largest surface that fits a budget. It then shows the arithmetic in every place the mode is displayed today, so the choice is never a black box. Two properties make it safe: the measurement is of real bytes, never an estimate; and a session keeps its surface for its lifetime, so long-lived agents never lose their prompt cache to a surface flip.
+
+This release ships `auto` as opt-in and instruments the decision. Whether it becomes the default is a separate decision, gated on the telemetry this feature collects.
+
+## Scope Boundary *(read before planning)*
+
+| Already exists | Reused, not rebuilt |
+|---|---|
+| Three routing surfaces and their built-ins: `retrieve_tools` + `describe_tool` + `call_tool_*`, direct full, direct deferred, `code_execution` | renderers, dispatch handlers, `describe_tool`, validation, self-healing errors |
+| Real tokenizer with JSON counting (cl100k_base by default) | candidate measurement |
+| Compact-signature cache (Spec 085/102) | deferred and compact rendering |
+| Profile scope, agent-token server restriction and permission tiers, per surface | catalog scoping |
+| Direct-surface catalog snapshot with fingerprint-guarded republish (Spec 102) | within-rung refresh |
+| Bench mode-cell names `direct_full` / `direct_deferred` / `retrieve_compact` (Spec 103) | rung naming, so bench, API and telemetry agree |
+
+**Release shape.** P1 (User Stories 1–4) is the smallest slice that is safe to expose: `auto` works on the default endpoint, sessions are stable, every request is authorized by its own scope, and the decision is visible in the routing API and `doctor`. P2 (Stories 5–6) adds hysteresis reporting, tray and Web UI rendering, and telemetry. P1 and P2 are internal milestones for ordering the work: **every FR and SC in this spec is required before the feature is enabled in a public release**; `auto` is not offered to users with only P1 landed. `auto` selects among existing surfaces; it adds no new built-in tool and no new tool argument to any fixed surface.
+
+**Prerequisite (Spec 105).** Eight behaviours of the existing fixed surfaces contradict "every request is authorized by its own scope" (cached responses, `set_profile` and profile-URL responses, `retrieve_tools` metadata, direct-publication filtering, target-tier execution permission, aggregated prompts, per-server management operations, legacy cache entries). They are specified and tested in Spec 105 and MUST ship before `auto` is enabled; this spec assumes them and does not restate them.
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 — The small-fleet developer gets the whole menu, and knows why (Priority: P1)
+
+A developer with two or three upstream servers (about 20 tools) sets `routing_mode: "auto"` and connects an agent to `/mcp`. The session receives every tool with its full schema — no search step, no `describe_tool` round trips — because the measured listing is well under the 12,000-token budget. When they run `mcpproxy doctor`, the routing line names the surface served, the tokens each candidate measured, and the budget.
+
+**Why this priority**: This is the population most likely to try mcpproxy and leave: for them the default mode is strictly worse than no proxy. It is also the cheapest rung to verify.
+
+**Independent Test**: Run a fixture proxy with ~20 tools under `auto`; open a session on `/mcp`; assert its `tools/list` carries the same upstream entries as `/mcp/all` configured for full serialization (same names, same schemas, same annotations) plus the enumerated built-ins for the active settings, and that the decision record shows `direct_full` with its measurement under the budget.
+
+**Acceptance Scenarios**:
+
+1. **Given** a catalog whose full direct listing measures under the budget, **When** a new session initializes on `/mcp`, **Then** its `tools/list` is the direct full surface — every visible upstream tool with full schema, plus the direct built-ins — and no search meta-tool.
+2. **Given** that session, **When** the agent calls an upstream tool by its listed name, **Then** the call dispatches exactly as it would on `/mcp/all`: same validation, same self-healing invalid-params errors, same scope and permission gates.
+3. **Given** that session, **When** the initialize response is read, **Then** its instructions are composed per FR-019 for the `direct_full` rung and end with one line naming the chosen rung and the budget.
+4. **Given** the session is open, **When** an administrator reads the routing API or runs `doctor`, **Then** each shows the chosen rung `direct_full`, the measured tokens for all three candidates, the budget, the per-candidate listed and discoverable counts, the scope label, the decision reason and the decision time.
+
+---
+
+### User Story 2 — The large-fleet developer stays under budget, per call (Priority: P1)
+
+A developer running ~1,000 tools turns on `auto`. Neither full nor deferred fits, so the session gets `retrieve_tools` with compact entries and `describe_tool`. Each search returns a handful of compact signatures; full schemas arrive only for the tools the agent chooses to inspect. The developer sees the three measured numbers side by side and understands that no direct rung could have fit.
+
+**Why this priority**: This is the population the headline savings claim is about. `auto` must never make them worse than the current default, and the observability must make "why not direct?" answerable without a support thread.
+
+**Independent Test**: Run a fixture proxy with the frozen 527-tool snapshot under `auto`; open a session; assert `tools/list` equals the `retrieve_tools`-mode surface as served by `/mcp/call` under the same code-execution and management settings, that `retrieve_tools` answers compact without an option, and that the decision record shows both direct candidates over budget.
+
+**Acceptance Scenarios**:
+
+1. **Given** a catalog where both direct candidates measure over the budget, **When** a new session initializes on `/mcp`, **Then** its `tools/list` is the `retrieve_tools` surface and `retrieve_tools` answers with compact entries (signature plus first-sentence description) without the agent passing any option.
+2. **Given** that session, **When** the agent passes `detail: "full"` on a single `retrieve_tools` call, **Then** that call is honoured exactly as on `/mcp/call` — the per-call override is the agent's choice and is outside the rung.
+3. **Given** that session, **When** the agent calls `describe_tool` for an id it retrieved, **Then** it receives the full definition, exactly as on `/mcp/call`.
+4. **Given** that session, **When** the decision record is read, **Then** every candidate's measurement is present and the two direct candidates are shown exceeding the budget, so the reason for the rung is self-evident.
+5. **Given** the same catalog under `routing_mode: "retrieve_tools"` with `tool_response_mode: "compact"`, **When** the two `tools/list` responses are compared, **Then** they are identical — `auto` on the bottom rung is the existing compact retrieve surface, not a fourth surface.
+
+---
+
+### User Story 3 — The middle-band developer is decided by the budget, not by a guess (Priority: P1)
+
+A developer with ~90 tools sits where full is over budget but deferred is under. Their session gets the deferred direct surface: every name with a one-line signature, schemas on demand. A colleague with ~200 tools and a larger model raises `context_budget_tokens` to 40,000 in config and, without restarting, their *next* session lands on deferred instead of `retrieve_tools`. Sessions already open keep the surface they started with.
+
+**Why this priority**: This is the band where fixed modes force the wrong choice and where the budget is the developer's steering wheel. It also exercises the two properties that make `auto` safe: the measurement is real, and the session contract is stable.
+
+**Independent Test**: With a catalog sized so that only deferred fits, assert the session gets the deferred direct surface (Spec 102 rendering); raise the budget via hot-reload; assert existing sessions are unchanged and a new session moves up a rung.
+
+**Acceptance Scenarios**:
+
+1. **Given** a catalog where full is over budget and deferred is under, **When** a new session initializes, **Then** its `tools/list` is the deferred direct surface — every tool with its compact signature appended, the permissive placeholder schema, `describe_tool` present — and the initialize instructions carry the deferral legend.
+2. **Given** an open session on any rung, **When** `context_budget_tokens` changes via config hot-reload, **Then** that session's surface does not change, no tools-list-changed notification is sent to it for that reason, and no restart is required.
+3. **Given** the budget change moves the measured catalog across the budget, **When** the next session initializes, **Then** it gets the rung that now fits; a budget change resets hysteresis history so the new budget is applied plainly.
+4. **Given** token counting is not available at runtime (disabled in config, or the tokenizer failed to initialize), **When** a session initializes under `auto`, **Then** the proxy serves the `retrieve_compact` rung and the decision record says the measurement was unavailable and why — a zero count is never treated as "fits".
+
+---
+
+### User Story 4 — A scoped session is measured on the catalog it will actually see, and only that (Priority: P1)
+
+A team pins a profile onto an agent token, restricts the token to a few servers, or grants it read-only permission. That session's catalog is a fraction of the fleet, so a 1,000-tool proxy can still hand a 15-tool profile the full direct surface. Two sessions on the same `/mcp` endpoint with different scopes get different rungs; each is measured on what its own scope can see; and every request is authorized by the scope it presents, never by the scope the session was decided for.
+
+**Why this priority**: Profiles and tokens are how large fleets are carved into usable slices; measuring the whole fleet for a scoped session would defeat `auto` for exactly the users who most need it. Because `/mcp` is agent-accessible, authorization correctness cannot be deferred to a later slice.
+
+**Independent Test**: On one proxy, open a session with a profile-pinned token whose scope fits full, and an unscoped administrator session whose fleet fits only `retrieve_compact`; assert the rungs differ, that each session can list, describe and call exactly what its own request scope allows (the unscoped session legitimately sees more), and that no registry, instruction, notification or decision-record state leaks between them.
+
+**Acceptance Scenarios**:
+
+1. **Given** a session whose token pins a profile, restricts servers, or limits permission tiers, **When** it initializes, **Then** the candidates are measured over the tools that scope can see on each rung — using that rung's own discovery predicate (the direct listing filters by permission tier; retrieve discovery filters by server scope and availability only, as today) — not over the whole fleet. A read-only token on the `retrieve_compact` rung can therefore discover and describe an approved destructive tool on an allowed server and cannot call it; on a direct rung that tool is not listed. This per-surface asymmetry is preserved, not changed.
+2. **Given** two concurrent sessions on `/mcp` with different scopes, **When** each lists tools, **Then** each receives the rung its own measurement chose, and each sees exactly what its own request scope allows and nothing more.
+3. **Given** two concurrent sessions whose tokens allow the same servers but carry different permission tiers, **When** each lists tools, **Then** each is measured and served on its own listing; they do not share a verdict.
+4. **Given** a session on the `retrieve_compact` rung that calls `set_profile` after initializing, **When** the profile narrows the catalog, **Then** the session's rung does not change, and the retrieve visibility filters apply the new scope exactly as they do today. The `set_profile` response lists only servers the caller's token may see, and an invalid selection from an agent token names no profiles it may not see (Spec 105 FR-003/FR-004). On a direct rung `set_profile` is not listed and is rejected exactly as on `/mcp/all` today.
+5. **Given** a later request on an existing session presents a token with a narrower or different scope than the one the session was decided for, **When** it lists, describes or calls tools, **Then** visibility and dispatch are gated by the scope of *that request*; the rung only ever governs serialization and which built-ins appear. A request that presents no valid credential where one is required is rejected as today.
+6. **Given** a decision record, **When** it is read by an administrator, **Then** it names the scope it was measured for (the profile slug, `token_scoped`, or `unscoped`) and never lists tool or server names.
+
+---
+
+### User Story 5 — The catalog grows and nothing flips on a 1% change (Priority: P2)
+
+A developer adds a server. Existing sessions keep their rung; their listings refresh within the rung exactly as today. If the addition pushes the measured catalog over the budget by more than the hysteresis band, the next new session lands on a lower rung; if it nudges it by a few percent, nothing changes. Removing the server later has the mirror behaviour with the same band, so a fleet hovering near the budget does not alternate rungs session to session.
+
+**Why this priority**: Long-lived agents rely on prompt caching; a surface flip mid-session throws that cache away. A fleet near the boundary would otherwise flip on every reconnect, which makes the mode look unstable and erodes trust in the decision.
+
+**Independent Test**: Start with a catalog that measures 95% of budget on the full rung and a first verdict of `direct_full`; add tools totalling 8% of budget (listing now 103%); assert 100 consecutive new sessions keep `direct_full`. Add tools bringing the listing to 115%; assert the very next new session drops a rung and every open session keeps its rung.
+
+**Acceptance Scenarios**:
+
+1. **Given** an open session on a direct rung, **When** an upstream server connects or disconnects, **Then** the session's rung is unchanged; its listing updates within the rung by the existing direct-surface refresh, which does not republish when the surface fingerprint is unchanged.
+2. **Given** the previous verdict for a scope is `direct_full` and the full listing now measures within the band above the budget, **When** a new session initializes, **Then** it still receives `direct_full`, with reason `held_by_hysteresis`.
+3. **Given** the full listing measures beyond the band, **When** a new session initializes, **Then** it receives the first eligible candidate in preference order per the FR-007 table (which can be the floor even when a lower rung fits the nominal budget but was ineligible before and has not cleared the band), and the decision record shows the previous rung and the crossing.
+4. **Given** the previous verdict is `direct_deferred` and the full listing shrinks back to within the band below the budget, **When** a new session initializes, **Then** it keeps `direct_deferred` until the full listing measures below the band — the band applies in both directions.
+5. **Given** no measurement input has changed since the last verdict for a measurement identity, **When** many sessions initialize, **Then** the proxy does not re-measure per session: the cached verdict is reused, so connect latency is not proportional to fleet size.
+
+---
+
+### User Story 6 — Every existing surface reports the decision honestly (Priority: P2)
+
+An operator turns on `auto` and looks in the places they already look: `/api/v1/status`, `/api/v1/routing`, `mcpproxy doctor`, `mcpproxy status`, the tray glance, the Web UI mode switcher, the telemetry heartbeat. Each says `auto` is the served mode and shows what it is entitled to show of the decision. None silently displays "Retrieve" because `auto` was an unknown word.
+
+**Why this priority**: Today an unrecognised routing value is folded to `retrieve_tools` when resolved, the Web UI falls back to "Retrieve" for unknown values, `doctor` reads the config file rather than the daemon, and telemetry reports the configured rather than the served mode. Any one of those left in place means an operator cannot tell whether `auto` is running.
+
+**Independent Test**: With `auto` running, read each surface as an administrator and assert it names `auto` and shows the projection defined in FR-021; with the daemon stopped, assert `doctor` reports `auto` as configured and states that no live decision is available.
+
+**Acceptance Scenarios**:
+
+1. **Given** `auto` is served, **When** an administrator reads `/api/v1/status` and `/api/v1/routing`, **Then** `routing_mode` is `auto`, `available_modes` includes `auto`, and the routing payload carries the latest verdict per measurement identity and the recent-verdict history.
+2. **Given** `auto` is served, **When** an agent-token caller reads `/api/v1/status` or `/api/v1/routing`, **Then** it sees `routing_mode: auto` and only the verdict for its own scope; the unscoped verdict, other scopes' verdicts, their catalog sizes and their profile names are withheld, as deployment-wide activation data is withheld from scoped callers today.
+3. **Given** `auto` is served, **When** `mcpproxy doctor` or `mcpproxy status` runs, **Then** it reports the served mode and the latest unscoped verdict from the running daemon; the CLI states in FR-022 (no daemon, unauthorized, daemon without the field, no verdict yet) each produce their defined output and exit status.
+4. **Given** `auto` is served, **When** the tray glance and the Web UI mode switcher render, **Then** each shows `auto` with the latest unscoped verdict's rung and measured-versus-budget figures; the settings selectors offer `auto` as a fourth option marked restart-required, as the other routing values are.
+5. **Given** a telemetry heartbeat from an install serving `auto`, **When** it is inspected, **Then** `routing_mode` is `auto`, the aggregate record of FR-026 is present with closed-enum keys and values only, and no tool, server or profile name appears; from an install not serving `auto` the record is absent, not zero-filled.
+6. **Given** an operator switches from a fixed mode to `auto` (or back), **When** the config is saved, **Then** the change is reported as restart-required exactly as other routing-mode changes are today, and the pending value shows in the routing API and Web UI.
+
+---
+
+### Edge Cases
+
+- **Catalog not yet settled at initialize.** Upstream servers connect and are discovered in the background, so the first sessions of a process would otherwise measure an empty or partial catalog, receive `direct_full`, and be stranded on a full-fleet listing when the rest arrives. A server is *settled* when its discovery has completed and its tools are published to the surfaces, or it is in a terminal error or disabled state, or 15 seconds have elapsed since its **admission**: the first connection attempt after the server was added, enabled, unquarantined, or had its connection configuration replaced. Automatic retries do not restart the deadline; repeated attempts inside the window settle at the original deadline whether or not a publication event occurs. Settlement is evaluated **per scope**: the catalog is settled for a scope when every enabled, non-quarantined server that scope may see is settled; servers outside the scope never affect it, so a scoped session neither waits for nor learns about servers it cannot see. Until settled for its scope, a new session is served the floor with reason `catalog_pending`; it keeps the floor for its lifetime like any other session. A scope with zero visible enabled servers is settled immediately. A server admitted while the process is running starts its own 15-second window for the scopes that may see it; sessions that initialize inside it get `catalog_pending`, and sessions after it are measured on whatever that server published. A server that keeps reconnecting counts as settled once its admission window has elapsed; its listing changes then flow through re-measurement like any other catalog change. The remaining risk — a slow server publishing after its window — is accepted and handled by re-measurement for later sessions.
+- **Fallback verdicts are transient.** `catalog_pending` ends when the catalog settles, whether or not that publishes a listing change; `measurement_error` is not cached — the next session re-measures; `tokenizer_unavailable` lasts until restart, because tokenizer configuration is restart-pinned today. Fallback verdicts never establish hysteresis history.
+- **Token counting unavailable.** The measurement component MUST know whether counting is available and which encoding it uses, distinguishing configured-off from initialization failure; both are reported as *unavailable* with their reason, never as a zero count. A direct rung is never inferred from tool counts, per-tool averages or the fleet-wide savings estimator.
+- **Session identity.** The client-facing HTTP surface is pinned to the protocol era that mints a session id per session; that pin stays. Transport validation takes precedence: a request without a valid session id, or with an id the proxy does not know (for example after a restart), is rejected by the protocol as today; there is no accepted no-session path on the default endpoint, and no request ever inherits another session's rung. A repeated `initialize` on an existing session keeps that session's binding.
+- **Serialization settings under `auto`.** The rung dictates serialization on the default endpoint: `tool_response_mode` and `direct_tool_response_mode` are not consulted there, and `doctor` says so when they are set while `auto` is served. They keep governing the dedicated endpoints. A hot-reload of either is not a measurement input and does not re-measure.
+- **Listing-affecting settings.** `enable_code_execution` (a live tool or a disabled stub on the retrieve rung; a live tool or absent on the direct rungs) changes what a rung lists; it is a measurement input, and a change re-measures for new sessions and refreshes open sessions within their rung exactly as it does on the fixed endpoints today. `disable_management` and `read_only_mode` also change the retrieve listing, but the listing is built once at startup today even though change reporting treats them as hot; for this feature they become **startup-pinned** measurement inputs in every mode: a change is reported as restart-required and pinned in the effective configuration (listed under FR-004), and no hot-toggle behaviour is specified or tested.
+- **`code_execution` on the direct rungs.** When enabled, the tool is present on every rung under `auto`, rendered as it is today on the surface that already carries it; its tokens are included in each candidate's measurement. On the direct rungs this is the one enumerated built-in delta from `/mcp/all`. Calls made from inside a script follow the existing code-execution authorization and dispatch contract (server and tool named separately), not the direct catalog's admission: a tool withheld from the direct listing because its flattened display name collides is still callable from a script, exactly as it is on `/mcp/code` today. Parity with `/mcp/all` (FR-011, FR-030, SC-005) is therefore defined over **direct-name dispatch**; nested script calls are compared with `/mcp/code`. A fixture with a display-name collision pins this. `set_profile` is not added to the direct rungs.
+- **Rung order is a preference order, not a size order.** With an empty or tiny catalog the direct listing (one built-in) can be smaller than the retrieve menu. The ladder is evaluated top-down: the first candidate that fits wins; `retrieve_compact` is served whenever no direct candidate fits, regardless of its own measurement. The decision record says "all candidates over budget" only when the measurements show it.
+- **Catalog changes during initialize.** The decision is bound to a measurement revision; a change landing between measurement and the first `tools/list` is handled by the existing within-rung refresh, not by re-deciding. The decision record keeps the revision it was measured on.
+- **Config reload churn.** Today a config reload republishes the `retrieve_tools` surface to all its clients without a change check. Under `auto` a budget or unrelated change MUST NOT cause a republish to sessions whose surface did not change (FR-012). This is a deliberate compatibility exception to FR-004.
+- **Availability predicates differ by surface.** The direct listing and the search index disagree by design on quarantined-but-lingering and pending tools, and agent-token callers and administrators see pending tools differently on the direct surface. Each candidate is measured with its own predicate for the caller kind and scope in question, so the number shown is the number that rung would ship. Display-name collisions withheld from the direct listing are withheld from the direct measurements too: measurement is of the served listing, never of the raw catalog.
+- **Scope definition edits.** Editing a profile's server list, a token's allowed servers or its permissions changes what that scope can see without changing the tool catalog; it is a measurement input, and it resets hysteresis history for that scope.
+- **Per-session state.** A session binding lives exactly as long as its transport session. Transport sessions end on explicit termination, at restart, or by **live-session idle expiry**: 30 minutes since the last request *completed* on that session with no request in flight, counted from initialize for a session that never sends another request. An in-flight tool call counts as activity and defers expiry until it completes (a 40-minute call on an otherwise idle session keeps the session alive and its binding intact); an open receiving stream does not count as activity and is closed when the session expires. A call still running when its session is explicitly terminated completes upstream but its result is not delivered, and neither a late completion nor a late stream write can resurrect an expired session or binding. Clock-controlled tests cover the 40-minute call and the idle stream. The expiry applies to every HTTP MCP session in every mode (a deliberate change, listed under FR-004). Expiry ends the transport session, so a request on an expired id is rejected as unknown (never served without its binding). This live expiry is distinct from the existing cleanup of persisted session history rows, which is unchanged. Initialize-only sessions appear in the administrator session projection as live sessions with no activity; persisted history rows never show a binding after the live session has ended. The retention bounds of FR-017 hold whether or not the transport reports session end.
+- **Dedicated endpoints and aliases.** `/mcp/all`, `/mcp/code`, `/mcp/call` and `/mcp/p/` keep their fixed modes and ignore the budget. The legacy aliases of `/mcp` are true aliases today and remain so: under `auto` they are auto-routed with `/mcp`.
+- **Budget below every candidate.** Hysteresis eligibility (FR-007) is applied first: a previously eligible direct candidate inside its band stays eligible and is served even when every measurement exceeds the nominal budget. Only when neither direct candidate is eligible and all three measurements exceed the nominal budget is the floor served with reason `budget_below_all`, and `doctor` warns. A fixture MUST cover the all-over-budget case with a previously eligible direct candidate inside the 110% band.
+- **Who may read decision records.** Administrators (API key or local socket) see all verdicts, history and session bindings. An agent-token caller sees only the latest verdict for its own scope, and only while that verdict's measurement identity still matches the caller's current authorization; when a profile or token is narrowed or deleted, the earlier broader record is withheld from that caller immediately (state `no_current_authorized_verdict`) while administrators keep it as history. Session endpoints stay administrator-only as today.
+- **Effective budget under an environment override.** When the environment variable is set, it is the effective budget: an API or file edit is persisted, reported by the API as `overridden_by_environment` with the effective value, and does not change verdicts or reset hysteresis. Without the override, an API edit is applied immediately and persisted, and a later reload of an unrelated file change keeps it.
+- **Invalid local config while the daemon runs.** If the local config file fails validation (for example `context_budget_tokens: 0`) while a daemon is running on the previous valid configuration, `doctor` and `status` still connect to the daemon and report the live decision; the local validation failure is reported as a separate finding, not as a reason to skip the live diagnostics.
+- **stdio transport.** stdio does not honour `routing_mode` today and continues to serve the default surface; `auto` is a property of the default HTTP endpoint only.
+
+## Requirements *(mandatory)*
+
+### Definitions *(binding)*
+
+- **Rung**: one of three candidate surfaces in preference order: `direct_full`, `direct_deferred`, `retrieve_compact`. Names are the bench mode-cell identifiers so bench, API and telemetry agree.
+- **Measured object**: the complete `tools/list` result a session would receive on that rung for its measurement identity — the tools array as rendered for serving (including deferred signature suffixes as they will actually be served, given the signature cache state at measurement time) plus any metadata the proxy adds to the result — serialized as the proxy serializes it, excluding only the JSON-RPC envelope. The proxy serves the listing unpaginated, so one page is the whole listing.
+- **Candidate measurement**: the token count of the measured object by the runtime tokenizer, labelled with the encoding name.
+- **Measurement identity**: every input that changes a candidate's measured object: the visible tool set with its hashes and annotations; per-tool approval and callability state as seen by the caller kind; the caller kind (administrator or agent) and the token's profile pin, server restriction and permission tiers (tiers affect the direct rungs' listing only; retrieve discovery is tier-blind, as today); the effective budget; and the listing-affecting settings (code execution; management and read-only as startup-pinned values). A dedicated endpoint's serialization setting is not an input.
+- **Scope label**: the redacted display form of the authorization part of a measurement identity: a tagged pair of **category** (`unscoped`, `token_scoped`, or `profile`) and, for `profile`, the slug. The category is a separate field, never inferred from the slug, so a profile literally named `unscoped` or `token_scoped` (both valid names today) is distinct from the categories in every record, projection and retention rule. Used in records and displays; never the key itself.
+- **Measurement revision**: an opaque identifier that changes whenever any input of a measurement identity changes. Recorded on every verdict.
+- **Verdict**: the rung chosen for one measurement identity at one revision, with its decision record.
+- **Session binding**: the rung and reason a session was served at initialize, immutable for the session's lifetime.
+- **Hysteresis**: see FR-007 and the transition table under it.
+- **Settled catalog**: see Edge Cases; the precondition for any verdict other than `catalog_pending`.
+
+### Functional Requirements
+
+**Configuration**
+
+- **FR-001**: `routing_mode` MUST accept the value `auto` in addition to the existing three. The value MUST pass config validation and MUST NOT be folded to `retrieve_tools` anywhere a mode is resolved or displayed. *Release-required*: the routing API's `available_modes`, and the tray and Web UI mode vocabularies and settings selectors, MUST recognise `auto` in the same release as FR-005, so no surface displays a fallback name.
+- **FR-002**: A setting `context_budget_tokens` MUST exist with default 12,000. Validation matrix: absent → default; `0` or negative → rejected with the field named; non-integer, overflowing or malformed environment value → rejected with the field named; when the environment variable is set it is the effective value and file or API edits are persisted but reported as `overridden_by_environment` (see Edge Cases).
+- **FR-003**: Switching to or from `auto` MUST be restart-gated, reported and pinned exactly as other `routing_mode` changes are today. Changing the effective `context_budget_tokens` MUST be hot-reloadable, reported as applied immediately with the field named, MUST affect only sessions that initialize after the reload, and MUST reset hysteresis history; an edit that does not change the effective value MUST NOT reset history.
+- **FR-004**: `auto` MUST be opt-in in this release; the shipped default remains `retrieve_tools`. With `auto` unset every existing surface MUST be identical to pre-feature behaviour, with these enumerated exceptions, each of which applies in every mode: FR-012 (notification suppression); the Spec 105 corrections (shipped separately, listed there); FR-022's daemon-discovery correction; `disable_management` and `read_only_mode` becoming restart-gated in change reporting and effective-config pinning (they are reported as hot changes today although the listing is built once at startup); and the live-session idle expiry of the Per-session state edge case, which applies to every HTTP MCP session regardless of mode.
+
+**Decision**
+
+- **FR-005**: At each new session's initialize on the default endpoint, the proxy MUST obtain a verdict for that session's measurement identity, and the session's first `tools/list` MUST already reflect it. Serving the verdict MUST NOT depend on a notification the client may never read.
+- **FR-006**: Candidate measurements MUST be made over the measured object as defined, with the runtime tokenizer, from the same rendered revision that will be served. Tool counts, per-tool averages and the fleet-wide savings estimator MUST NOT be used to decide.
+- **FR-007**: The chosen rung MUST be the first candidate in preference order that is eligible; `retrieve_compact` is the unconditional floor. Eligibility with hysteresis (band = 10% of budget, fixed):
+
+ | Situation for a candidate | Eligible when |
+ |---|---|
+ | No history for this scope (first verdict, after restart, after a budget change or a scope-definition edit) | measurement ≤ budget |
+ | History exists and the candidate was eligible in the previous verdict | measurement ≤ budget × 1.10 |
+ | History exists and the candidate was not eligible in the previous verdict | measurement < budget × 0.90 |
+
+ Comparisons are exact: a previously ineligible candidate at exactly budget × 0.90 stays ineligible; a previously eligible candidate at exactly budget × 1.10 stays eligible. History per scope records the previous verdict's rung and each candidate's eligibility. Multi-rung transitions are allowed: the first eligible candidate wins whatever the previous rung was, and a lower rung that fits the nominal budget but was ineligible before and has not cleared the band is skipped — the floor is served (accepted, symmetric hysteresis). Fallback verdicts do not write history.
+- **FR-008**: Settlement for the session's scope (Edge Cases) MUST be checked before any verdict is reused, independently of the measurement revision: a newly admitted in-scope server inside its window yields `catalog_pending` even though no listing changed, and a cached successful verdict is reused again once the scope is settled (a fixture covers cached verdict → delayed admission → pending → settlement by deadline without any tool publication). Otherwise verdicts MUST be reused for subsequent sessions with the same measurement identity until the measurement revision changes **or the scope's hysteresis history expires**; either event MUST trigger re-decision for the next session only, never a change to sessions already open (measured bytes may be reused across a history expiry; the decision may not). A verdict does not outlive its scope's history: when the history expires 24 hours after the scope's last session ends, the cached verdict is dropped with it. For display only, the administrator projections retain one **last-bound record** per scope label — keyed by category plus slug, so the administrator-unscoped record is never replaced by a profile named `unscoped` (tested) — marked `historical`, never reused for routing, bounded by the number of scope labels seen since start and independent of the 20-record rolling history so that after expiry the API, CLI and UI show that historical record with state `no_retained_verdict` rather than a fabricated no-session state. Telemetry is excluded from this projection: its record carries no state field, and after expiry its measurement bucket reports `none`. The clock-controlled expiry fixture asserts those projections before another session connects, and a second fixture binds more than 20 scoped verdicts after an unscoped session ends and then lets the unscoped verdict expire, asserting the historical unscoped record is still displayed. Fallback verdicts follow the transience rules in Edge Cases. Two independently seeded clock-controlled tests MUST cover history expiry with identical measurements at 95% of budget: (a) a scope whose last session ended, reconnecting 23 hours later, observes the held rung and — because that session renews retention when it ends — the same scope reconnecting 25 hours after *that* session ends observes a plain-fit decision; (b) a scope with two overlapping sessions, where ending one does not start expiry while the other remains live. After recovery from `catalog_pending` the reused verdict is reported per FR-021's binding-order rule.
+- **FR-009**: A session MUST keep its rung for its lifetime. No catalog change, budget change, profile selection, or config reload may change an open session's rung or emit a tools-list-changed notification to it for that reason. Within-rung refreshes (server connects and disconnects, listing-affecting setting changes) behave as they do on that rung's fixed endpoint today.
+- **FR-010**: When measurement is impossible — catalog not settled, counting unavailable, measurement error — the proxy MUST serve `retrieve_compact` and record the reason (`catalog_pending`, `tokenizer_unavailable`, `measurement_error`).
+- **FR-011**: Each rung served under `auto` MUST be behaviourally identical to the same surface on its fixed endpoint configured for the corresponding serialization (`direct_full` ↔ `/mcp/all` with full direct serialization; `direct_deferred` ↔ `/mcp/all` with deferred serialization; `retrieve_compact` ↔ `/mcp/call` with compact retrieve serialization), under the same code-execution, management and read-only settings: same upstream tool set, same serialization, same visibility predicates, same scope and permission gates, same dispatch validation and error shapes. The only permitted built-in delta is `code_execution` on the direct rungs when enabled.
+- **FR-012**: A config reload MUST NOT republish the `retrieve_tools` surface to sessions whose surface is unchanged; unchanged surfaces MUST be detected as they are for the direct surface today. This applies whether or not `auto` is served. On the `auto` endpoint, additionally, every list-changed notification — tools **and prompts** — MUST be decided **per recipient** (as defined in FR-016e): a recipient is notified only when its own authorized, serialized listing (tool listing or prompt listing respectively) changed. A prompt change on an inaccessible server produces no prompt-list notification to a recipient that cannot see it; the A-POST/B-stream and credential-narrowing cases of FR-016e are tested for prompt notifications as well. A catalog change that leaves a recipient's authorized listing unchanged produces no notification to it, so fleet activity is not signalled to recipients that cannot see it; a change that alters the authorized listing is notified without changing the rung. Deliberate exceptions, all of the same shape: display-name collision admission on the direct surface, prompt-name collision admission, and the global prompt cap are fleet-wide (retained by Spec 105), so a change on an inaccessible server can remove or restore an entry in a scoped tool or prompt listing; that listing change **is** notified, because withholding it would leave the recipient with a stale listing, and the fixed surfaces already expose the same withholding. Fixtures with a token allowed only server `a` pin each: a tool collision introduced on inaccessible `a__b`, a prompt collision introduced on `a__b`, and a prompt-cap displacement caused by `b`. The fixed endpoints keep their fleet-wide notification behaviour, which is why the within-rung parity of FR-009 and FR-011 is a parity of listing content and dispatch, not of notification delivery.
+- **FR-013**: The dedicated endpoints and the profile-URL endpoint MUST keep their fixed modes and MUST ignore the budget. The legacy aliases of the default endpoint remain aliases and follow it.
+- **FR-014**: The client-facing protocol-era pin that guarantees a session id MUST be retained and covered by a test that fails if it is lifted.
+- **FR-015**: Under `auto`, the global `tool_response_mode` and `direct_tool_response_mode` settings MUST NOT influence the default endpoint; the per-call `detail` override on `retrieve_tools` MUST keep working on the `retrieve_compact` rung.
+
+**Visibility and security**
+
+- **FR-016**: Discovery, description and dispatch on every request MUST be gated by the authorization of that request; the rung MUST govern only serialization and which built-ins appear. Discovery authorization (server scope, availability, approval; plus permission tier on the direct rungs only) and execution permission (tier at dispatch) remain the separate checks they are today. A request presenting a narrower or different token than the one the session was decided for MUST NOT discover, describe, call, or retrieve from cache anything outside its own authorization, and MUST NOT be able to read a decision record that belongs to a scope it is not entitled to. The fixed-surface corrections that make this true are Spec 105 FR-001–FR-009.
+- **FR-016e**: A list-changed notification's (tools **and prompts**) **recipient is the authenticated receiving stream or request**, never the session id alone. A notification is authorized against the credential that opened the receiving stream, at delivery time; a stream whose credential has since been narrowed, revoked or expired is closed rather than served. Tests MUST cover a session initialized with broad token A whose notification stream is opened with narrow token B while another request on the same session uses A (B's stream learns nothing A-only), and a credential narrowed after the stream opened.
+- **FR-017**: Retention bounds, each independently testable: session bindings ≤ live sessions (released on termination, idle expiry, or restart); cached verdicts ≤ live measurement identities, with verdicts of superseded revisions dropped once each live identity has a newer verdict; hysteresis history ≤ scopes seen, kept for 24 hours after that scope's last session ends so a reconnecting scope keeps its hysteresis; recent-verdict history ≤ 20 records.
+- **FR-018**: Local decision records MUST NOT contain tool names, server names, descriptions or schemas. The scope label MAY be the caller's own profile slug; an agent-token caller MUST be shown only the verdict for its own scope, never the unscoped verdict, other scopes' verdicts, their catalog sizes or their profile names. Session endpoints remain administrator-only.
+
+**Instructions**
+
+- **FR-019**: The initialize response under `auto` MUST be composed, per session and without mutating shared state, as: (1) the rung's base text — the direct instructions for the direct rungs, the `retrieve_tools` instructions for the floor; (2) if the operator configured custom `instructions`, that text replaces the base text on every rung, as it does on the direct endpoint today; (3) on `direct_deferred`, the deferral legend is appended; (4) one line naming the chosen rung and the budget is appended last. Where the fixed retrieve endpoint currently carries no default instructions over HTTP, the floor under `auto` uses the `retrieve_tools` default text; this is a named addition. That text's guidance about management tools (`upstream_servers`) MUST appear only when the management tools are actually listed for that session (they are absent under `disable_management` or `read_only_mode`); operator-supplied instructions and the fixed-surface goldens are unaffected, and initialize instructions are tested under both disabling settings.
+
+**Observability — decision record and projections**
+
+- **FR-020**: A decision record MUST exist for every verdict, carrying: chosen rung; decision reason (`fitted`, `held_by_hysteresis`, `catalog_pending`, `tokenizer_unavailable`, `measurement_error`, `budget_below_all`); for each of the three candidates its measured tokens (or `unavailable` with reason) and two separately named count pairs — *listed* upstream tool count and the number of servers represented among those listed entries (built-ins excluded), and *discoverable* upstream tool count and the number of servers with at least one discoverable tool under that rung's discovery predicate for the scope (so a destructive-only server seen by a read-only token counts on the retrieve rung and not on the direct rungs; an empty fleet reports zeros); budget; hysteresis band; tokenizer encoding name; scope label; measurement revision; decision timestamp; the previous rung for that scope; **the prior per-candidate eligibility used for this decision's comparisons** (three values, or an explicit `no_history` state after a reset, restart or expiry); and whether hysteresis held the previous rung. Counts are `n/a` when the measurement is unavailable. A test MUST cover two decisions with the same previous rung but different prior eligibility for `direct_deferred` (e.g. previous rung `direct_full`, full now at 115%, deferred at 95%) and assert the differing outcomes are reconstructible from their records alone.
+- **FR-021**: Projection matrix — the three objects are distinct and each surface shows exactly these:
+
+ | Surface | Administrator sees | Agent-token caller sees |
+ |---|---|---|
+ | `/api/v1/routing` | latest verdict per measurement identity (scope label, full record); recent-verdict history | latest verdict for its own scope only |
+ | `/api/v1/status` | `routing_mode: auto`; latest unscoped verdict's rung and reason | `routing_mode: auto`; own-scope rung and reason |
+ | session listing | each session's binding (rung, reason, revision) | not available (administrator-only) |
+ | `doctor`, `status` CLI | latest unscoped verdict, full record | n/a (administrator credential) |
+ | tray, Web UI | latest unscoped verdict's rung, measured-versus-budget figures, reason | n/a |
+ | heartbeat | aggregate of FR-026 only | n/a |
+
+ "Latest verdict" in every projection and in the telemetry measurement bucket means **the verdict most recently bound to a session** (binding order), not the most recently evaluated one; a cached verdict reused after a `catalog_pending` interval therefore becomes the latest again the moment a session binds to it, without any new measurement. The FR-008 delayed-admission fixture asserts routing, status, CLI and the telemetry bucket after recovery.
+
+ No-decision states are defined **per requested projection**, never fabricated: `no_session_evaluated` (the daemon is healthy and no session of any scope has initialized on an **auto-routed endpoint** — the default endpoint and its aliases — since start; sessions on the fixed endpoints do not count, though they remain visible in the administrator session listing, and the wording is "no auto-routed session has connected"; a fixture initializes only a `/mcp/all` session and asserts this state); `no_retained_verdict` (a verdict existed but expired with its history — the historical last-bound record is shown, marked as such); `no_unscoped_verdict` (only scoped sessions have initialized — the administrator projections then show the most recent verdict of any scope, carrying its scope label, rung, reason and measured figures, and say that no unscoped session has connected); `catalog_pending` and `tokenizer_unavailable` only when a session actually received that fallback; and, for agent-token callers, `no_current_authorized_verdict` when the caller's authorization no longer matches the latest record for its scope. The status API's administrator projection carries the alternate scoped record in the `no_unscoped_verdict` state so the CLI can render it; the CLI reads the administrator routing projection when it needs the full record. When several scopes have verdicts, the administrator default display is the unscoped verdict with a count of other scopes.
+- **FR-022**: `mcpproxy doctor` and `mcpproxy status` MUST report the served mode and the unscoped verdict from the running daemon. State table (text and JSON output; exit statuses use the existing CLI codes):
+
+ | State | Output | Exit |
+ |---|---|---|
+ | running, `auto`, verdict present | full decision record | 0 |
+ | running, `auto`, `no_session_evaluated` | "no decision yet: no auto-routed session has connected" | 0 |
+ | running, `auto`, `no_unscoped_verdict` | "no unscoped session has connected; latest scoped decision:" followed by that record with its scope label | 0 |
+ | running, `auto`, `no_retained_verdict` | "last decision expired; historical:" followed by the last-bound record marked historical | 0 |
+ | running, `auto`, latest binding is a fallback | its reason (`catalog_pending`, `tokenizer_unavailable`, `measurement_error`) | 0 |
+ | running, fixed mode | that mode, no decision line | 0 |
+ | daemon reachable, request unauthorized | "unauthorized" with the credential source tried | 5 |
+ | daemon reachable, response malformed or request failed | "daemon responded but the decision could not be read" | 1 |
+ | daemon reachable, older than this feature (field absent) | "decision not reported by this daemon version" | 0 |
+ | no daemon reachable | configured value with "no live decision available" | `status`: 0 (unchanged today); `doctor`: 1 (unchanged today) |
+ | local config invalid, daemon running | live state as above, plus a separate config-validation finding | as above |
+
+ *(prerequisite correction)* Daemon discovery MUST distinguish an authorization failure from a connection failure, so the unauthorized and no-daemon states are never conflated. `doctor` MUST warn on `budget_below_all` and MUST note when `tool_response_mode` or `direct_tool_response_mode` is set while `auto` is served.
+- **FR-023**: The tray and the Web UI MUST render `auto` as the served mode and the full FR-021 projection for their row: the Web UI mode switcher shows the chosen rung, reason and measured-versus-budget figures; the tray shows the served mode, current rung, reason and measured-versus-budget figures.
+- **FR-024**: Documentation for routing modes, configuration, the REST API and the CLI MUST describe `auto`, the budget, the preference ladder, the settled-catalog rule, the hysteresis table and the projection matrix, with worked figures at the default budget for a reproducible baseline: the frozen 45-tool and 527-tool corpora, administrator scope, code execution disabled, management enabled, warm signature cache, cl100k_base.
+
+**Telemetry**
+
+- **FR-025**: The heartbeat MUST report `routing_mode` as the served mode (`auto`), correcting the current behaviour of reporting the configured value.
+- **FR-026**: The heartbeat MUST add an aggregate auto-routing record, present with zero-valued counters whenever `auto` is served and absent otherwise, reset on each accepted send as other window counters are (the existing in-flight loss window between snapshot and reset is accepted). Typed domains:
+
+ | Field | Domain | Semantics |
+ |---|---|---|
+ | bindings by rung | histogram keyed by the three rung names → non-negative integer | session bindings created in the window (served-session distribution, cache hits included) |
+ | bindings by reason | histogram keyed by the six reasons → non-negative integer | same window |
+ | verdict decisions | non-negative integer | fresh verdict decisions in the window — including decisions made from cached measurements after a history expiry, excluding bindings that reuse a cached verdict |
+ | held by hysteresis | non-negative integer | of those fresh decisions, the number with reason `held_by_hysteresis` |
+ | budget bucket | enum `le_4k, le_8k, le_12k, le_24k, le_48k, gt_48k` | effective budget at send time |
+ | unscoped measurement bucket | enum `none, unavailable, le_2k, le_6k, le_12k, le_24k, le_50k, le_100k, le_200k, gt_200k` | latest unscoped verdict's `direct_full` measurement at send time; `none` when no unscoped verdict exists or the last one has expired (historical display records are not reported) |
+ | distinct scope labels | enum `1, 2_3, 4_9, ge_10` | distinct labels with a binding in the window; `1` when idle |
+
+ Scopes are aggregated; no per-scope breakdown.
+- **FR-027**: The telemetry schema version MUST be bumped; the anonymity scanner MUST gain a shape rule for the new record that rejects unknown keys, non-integer or negative counters, and any categorical value outside its enum; the telemetry documentation MUST be brought current with the code.
+
+**Surface stability**
+
+- **FR-028**: The feature MUST add no built-in tool and no tool argument to any fixed surface; the existing tool-surface goldens for the fixed surfaces MUST pass unregenerated. The `auto` default endpoint MUST get its own goldens per rung, per code-execution setting.
+- **FR-029**: A regression test MUST assert that a session's rung survives an upstream server connect, an upstream disconnect, a budget hot-reload, a serialization-setting hot-reload, a listing-affecting setting change, and — for a retrieve-rung session — a `set_profile` call; and that an out-of-scope server change produces no notification to a scoped session while an in-scope listing change does (FR-012).
+- **FR-030**: A visibility-parity test MUST assert, for each rung, that an `auto` session and a fixed-mode session with the same measurement identity agree exactly on what they can list, describe and call — including quarantined, pending, permission-tiered and out-of-scope cases — and a concurrency test MUST cover sessions with equal server scopes but different permissions, sessions with disjoint scopes, and a token change between initialize, list, describe and call.
+
+### Key Entities
+
+- **Verdict**: the rung chosen for one measurement identity at one revision, with its decision record; reused until the revision changes.
+- **Decision record**: the observable explanation of a verdict (FR-020), projected per FR-021.
+- **Session binding**: the rung and reason a given session was served, fixed at initialize, exposed to administrators in the session listing, released at session end.
+- **Hysteresis history**: per scope, the previous verdict's rung and per-candidate eligibility; reset by budget change and scope-definition edits; expires 24 hours after the scope's last session.
+- **Budget policy**: `context_budget_tokens` plus the fixed 10% band; hot-reloadable; consulted only at verdict time.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: On the frozen 45-tool corpus at the default budget under the FR-024 baseline, a new `auto` session receives the same upstream entries as `/mcp/all` in full serialization with only the enumerated built-in delta; on the 527-tool snapshot it receives the same `tools/list` as `/mcp/call` in compact serialization. Both asserted in automated tests.
+- **SC-002**: For every successful (non-fallback) verdict whose measurement identity and revision are unchanged between decision and first listing, the recorded measurement of the chosen rung equals an independent tokenizer count of the measured object the session actually received. Separately, for every candidate ahead of the chosen rung in preference order, the record shows either `unavailable` or a measurement that fails that candidate's exact FR-007 eligibility predicate given the recorded history (e.g. a previously ineligible candidate at exactly budget × 0.90 is correctly ineligible).
+- **SC-003**: Starting from a `direct_full` verdict on a listing at 95% of budget, growth to 103% leaves 100 consecutive new sessions on `direct_full` with reason `held_by_hysteresis`; growth to 115% drops the very next session a rung; every open session keeps its rung in both runs. From `direct_deferred`, shrinking the full listing to 92% keeps `direct_deferred`; shrinking to 88% promotes the next session.
+- **SC-004**: Connect latency, measured from the initialize request arriving to the initialize response leaving, on the 527-tool snapshot, 200 sequential sessions after warm-up, on the CI reference runner: p95 under `auto` with a cached verdict is within 50 ms of p95 under `retrieve_tools`; the first verdict after a revision change completes within 500 ms at p95.
+- **SC-005**: For every scoped session in the profile and agent-token integration suites, the tool set listed, describable and callable is identical between `auto` (on whichever rung it lands) and the corresponding fixed mode — zero visibility widening — and the FR-030 concurrency test shows no state shared between sessions.
+- **SC-006**: With a fixture whose upstreams publish with a delay: a session initializing before settlement gets `catalog_pending`, keeps it after the fleet publishes, and a session initializing after settlement gets the fitted rung; when settlement occurs by deadline without any tools arriving, the next session gets a fitted verdict, not `catalog_pending`; after an injected measurement error, the next session re-measures successfully.
+- **SC-007**: Every reporting surface in the FR-021 matrix shows its defined projection for `auto`, including each no-decision state, and a test enumerates the surfaces and asserts none displays a fallback mode name.
+- **SC-008**: The telemetry anonymity scan rejects a heartbeat whose auto-routing record carries an unknown key, a negative or non-integer counter, or a categorical value outside its enum, and accepts a record with legitimate integer counts; no string in the heartbeat matches any tool, server or profile name in the fixture fleet; local decision records contain no tool or server name and, for an agent-token caller, no profile name other than its own.
+- **SC-013**: With a broad token and a narrow token on one session: CLI discovery against a daemon with a wrong API key and no socket reports unauthorized (exit 5), not "no daemon" (FR-022); and the A-POST/B-stream and narrowed-credential cases deliver nothing to the narrower stream for tools and prompts (FR-016e). Spec 105's SC-001–SC-004 are prerequisites and are not repeated here.
+- **SC-009**: All existing tool-surface goldens for the fixed surfaces pass unregenerated on the feature branch.
+- **SC-010**: `doctor` output under `auto` contains, in its documented format, the chosen rung, the decision reason, the three measured figures and the budget; a test compares the live output to the documented sample for each FR-022 state.
+- **SC-011**: After N sessions across M scopes open and end, retained session bindings are zero after expiry, cached verdicts are ≤ M, hysteresis histories are ≤ M, and the recent-verdict history is ≤ 20, for N ≫ M.
+- **SC-012**: Instrumentation acceptance: in the integration suite, on a quiescent snapshot (no session activity between payload construction and the accepted send), the heartbeat record's binding counts equal the sessions opened in the window and its decision count equals the fresh verdict decisions made (a history-expiry re-decision from cached measurements counts one decision and zero measurements; a cached-verdict binding counts one binding and zero decisions — tested separately). An idle window yields zero counters and distinct-label bucket `1` while the budget bucket and the latest-unscoped measurement bucket retain their current values; the measurement bucket is `none` only when no unscoped verdict exists, asserted separately. Operational KPI (not a merge gate): the record is present in at least 95% of heartbeats from installs serving `auto` in the release's first 30 days.
+
+## Assumptions
+
+- **Worked figures** in this spec (528,322 / 300,893 tokens for a 1,016-tool fleet; the frozen 45-tool and 527-tool corpora) come from existing measurements; they motivate the design but never enter the decision — FR-006 measures the real listing.
+- **The hysteresis band is fixed at 10%** and is not a configuration knob; one knob (`context_budget_tokens`) is enough for this release.
+- **Scope at verdict time** is what initialize can see: caller kind and the token's profile pin, server restriction and permission tiers. A `set_profile` selection made after initialize narrows visibility within the rung but does not re-decide.
+- **Candidate measurements use each rung's own visibility predicate** for the caller kind in question, because that is what each rung would actually serve; no unified predicate is introduced.
+- **The settlement window is 15 seconds from admission** (first attempt after add, enable, unquarantine or connection-config replacement; retries do not extend it), chosen to cover normal stdio-server startup while keeping the first session's wait bounded; the partial-catalog risk for servers slower than that is accepted and corrected by re-measurement for later sessions.
+- **Tokenizer configuration is restart-pinned**, as it is today; the runtime tokenizer's availability and encoding name are exposed to the measurement component.
+- **`disable_management` and `read_only_mode` are startup-pinned** for the purposes of this feature; making them hot-reloadable is a separate change.
+- **Live-session idle expiry of 30 minutes** matches the existing persisted-session cleanup interval so operators see one number.
+- **The per-session serving mechanism** is a planning choice (a session-aware listing with per-session serialization, or per-session tool registration). The binding constraints are FR-005, FR-009, FR-016 and FR-019.
+- **Bench is unchanged**: `auto` sessions report one of the existing mode-cell ids, so bench and telemetry share vocabulary without a new cell.
+- **Default flip** is out of this release. The metric it will be gated on is FR-026's served-session distribution; the threshold is decided in the follow-up spec, not here.
+- **Tokenizer specificity**: measurements and the budget are figures for the runtime encoding (cl100k_base by default) and are labelled with it; documentation states that other models' tokenizers count differently and gives no universal bound.
+
+## Out of Scope
+
+- A fourth surface, a new built-in tool, or a new tool argument on a fixed surface.
+- Per-session rung changes, client-declared budgets via headers, or any mid-session renegotiation.
+- Applying the budget to `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/`, or stdio.
+- Changing which quarantined, pending or disabled tools each surface shows, or how agent-token callers see pending tools.
+- Making `auto` the default, or a configurable hysteresis band.
+- Lifting the legacy protocol-era pin on the client-facing HTTP surface.
+- Agent-token access to session endpoints.
+
+## Commit Message Conventions *(mandatory)*
+
+When committing changes for this feature, follow these guidelines:
+
+### Issue References
+- ✅ **Use**: `Related #[issue-number]` - Links the commit to the issue without auto-closing
+- ❌ **Do NOT use**: `Fixes #[issue-number]`, `Closes #[issue-number]`, `Resolves #[issue-number]` - These auto-close issues on merge
+
+**Rationale**: Issues should only be closed manually after verification and testing in production, not automatically on merge.
+
+### Co-Authorship
+- ❌ **Do NOT include**: `Co-Authored-By: Claude `
+- ❌ **Do NOT include**: "🤖 Generated with [Claude Code](https://claude.com/claude-code)"
+
+**Rationale**: Commit authorship should reflect the human contributors, not the AI tools used.
+
+### Example Commit Message
+```
+feat: [brief description of change]
+
+Related #[issue-number]
+
+[Detailed description of what was changed and why]
+
+## Changes
+- [Bulleted list of key changes]
+- [Each change on a new line]
+
+## Testing
+- [Test results summary]
+- [Key test scenarios covered]
+```
diff --git a/specs/105-agent-scope-hardening/checklists/requirements.md b/specs/105-agent-scope-hardening/checklists/requirements.md
new file mode 100644
index 000000000..0607ddaff
--- /dev/null
+++ b/specs/105-agent-scope-hardening/checklists/requirements.md
@@ -0,0 +1,56 @@
+# Specification Quality Checklist: Agent-Token Scope Hardening
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-09-07
+**Feature**: [spec.md](../spec.md)
+
+## Content Quality
+
+- [x] No implementation details (languages, frameworks, APIs) — surfaces and built-ins are named; no packages or types
+- [x] Focused on user value and business needs
+- [x] Written for non-technical stakeholders
+- [x] All mandatory sections completed
+
+## Requirement Completeness
+
+- [x] No [NEEDS CLARIFICATION] markers remain
+- [x] Requirements are testable and unambiguous
+- [x] Success criteria are measurable
+- [x] Success criteria are technology-agnostic (no implementation details)
+- [x] All acceptance scenarios are defined
+- [x] Edge cases are identified
+- [x] Scope is clearly bounded (agent-token callers only; administrators unchanged)
+- [x] Dependencies and assumptions identified (Spec 104 depends on this; five fix sessions in flight)
+
+## Feature Readiness
+
+- [x] All functional requirements have clear acceptance criteria
+- [x] User scenarios cover primary flows
+- [x] Feature meets measurable outcomes defined in Success Criteria
+- [x] No implementation details leak into specification
+
+## Notes
+
+- Origin: the eight corrections were discovered by the cross-model review of Spec 104 (rounds 2–9, opencode `github-copilot/gpt-6-astra`, 2026-09-07) and split out at the maintainer's direction so Spec 104 can converge without carrying fixed-surface changes.
+- Validation pass 1 (2026-09-07): all items pass.
+- Cross-model review round 1 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 21 findings (10 high). All applied in a rewrite: effective-authorization provenance with superset redemption (FR-001); legacy and internal entries refused for all callers with durable invalidation (FR-002, named administrator exception); every redemption door and producer covered; target-tier resolution from the exact dispatched identity, fail-closed on unresolvable metadata, paired-name case, permission×tier×variant table with zero-upstream-call oracle (FR-009); scope filtering before limiting with corpus-wide scoring retained and documented (FR-005); publication filtering at every seam, both skew directions, malformed names withheld, built-ins positively identified (FR-008); prompts fail closed on unknown ownership with interleaving tests (FR-006); log-resource ownership for colliding file names (FR-007); MCP-only transport scope with REST policy out of scope; profile selection predicate (intersection) and profile-URL parity (FR-003/FR-004); non-disclosing dispatch and available-server errors (FR-010); one strict-validation boolean; applicability matrix (FR-014); differential two-fixture oracle with sentinels (FR-013, SC-001); reproducible performance bounds (FR-011); retained effects enumerated in the invariant (FR-012); SC-007 restated as a regression-suite requirement. Items where the in-flight fix sessions were briefed more narrowly are marked ⚠ in the spec.
+- Validation pass 2 (2026-09-07): all items pass; zero clarification markers.
+- Cross-model review round 2 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 3 findings, all applied: corpus-wide scoring effects (score, ordering, top-K membership) excluded from the differential oracle and "not displaced" defined against the same-corpus filtered top-K with a multi-term fixture; the profile-URL endpoint applies the selectable-profile predicate (FR-004); execution acceptance split into a retrieve table with variants and a direct/nested table without, with permission-disallowed and intent-mismatch cells classified separately (FR-009, SC-002).
+- Validation pass 3 (2026-09-07): all items pass; zero clarification markers.
+- Cross-model review round 3 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 3 findings, all applied: `describe_tool` case-suggestion existence oracle closed by one suggestion policy over the authorized corpus, added to the applicability matrix (FR-010, FR-014); permission-disallowed cells include a missing variant tier on retrieve dispatch, classified before intent mismatch (FR-009); retained admission effects exempted from cross-fixture equality with their own assertions (SC-001, FR-013).
+- Cross-model review round 4 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 3 findings, all applied: direct-surface display/canonical resolution over the authorized corpus with a cross-namespace fixture (FR-010); every policy gate (denial, approval, callability) evaluated on the exact dispatched pair with same-tier paired-name tests (FR-009); ranking-derived `explain_tool` fields added to the oracle exclusions (Edge Cases).
+- Cross-model review round 5 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 medium, both applied: refusal precedence defined (scope violations non-disclosing; tier denials on authorized servers disclose insufficient permission on every dispatch path) in FR-010 and Definitions; native stdio excluded as administrator-only.
+- Cross-model review round 6 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 medium, both applied: custom initialization instructions and stored-script names/constant output classified as operator-published content outside the semantic guarantee with a documentation warning and fixtures; missing-script errors made non-disclosing for agent tokens; nested calls stay scope-checked (Edge Cases, FR-012, FR-014).
+- Cross-model review round 7 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 1 medium, applied: empty profiles exempted from the unrestricted-token compatibility promise (refused to every agent token through both paths; administrators unchanged) with a fixture.
+- Cross-model review round 8 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 1 medium, applied: FR-006 no longer treats an unparseable display name (owner beginning with `__`, a valid server name) as unknown ownership — the registration identity records the owner, so unrestricted agents keep that prompt; unknown ownership is only a missing registration identity. Fixture with server `__a` added.
+- Cross-model review round 9 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 5 medium, all applied: FR-008 aligned with FR-006 (withhold only for a missing registration identity; `__a` direct-tool fixture); unrestricted-agent compatibility exceptions enumerated (empty profile, exact-identity policy gates, missing registration identity) and mirrored as administrator exceptions in SC-005 with an empty-raw-name fixture; REST direct call path's cache branch named as a narrow exception to REST exclusion (FR-001); one shared retrieve oracle that also excludes truncation/size/pagination consequences of permitted ranking changes.
+- Cross-model review round 10 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 3 findings (1 high), all applied: identity preservation extended to approval creation, baseline capture, index updates and publication with a real-discovery fixture and conservative legacy-approval handling (FR-009); SC-003 aligned with the corrected malformed-display rule; one administrator exception list (SC-005) referenced from Scope Boundary, Edge Cases and FR-012.
+- Cross-model review round 11 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 3 findings (1 high), all applied: REST cache redemption includes the token's profile pin with a pinned-token fixture; the administrator exception list now covers the discovery/index consequences of raw-identity preservation with a positive both-approved fixture; publication dispatch expectations defined by the handler registered at each seam.
+- Cross-model review round 12 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 1 medium, applied: the retrieve oracle now derives the per-fixture expectation as authorized hits → ranked window → existing annotation filters, and excludes `total` and the complete filter-diagnostics payload from cross-fixture equality (FR-005, US1.5).
+- Cross-model review round 13 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 3 medium, all applied: container-resource ownership in Docker cleanup/logging with an `a` vs `a-b` fixture (FR-007); shared-limiter contention retained as a documented effect with a held-call fixture; internal cache entries added to the administrator exception list with a fresh-entry test (SC-005).
+- Cross-model review round 14 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 medium, both applied: cross-server security-scan admission retained as a documented effect with a real-discovery fixture and oracle exclusion; FR-007 container-ownership housekeeping outcomes added to the administrator exception list.
+- Cross-model review round 15 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 medium, both applied: shared prompt-refresh deadline retained as a documented effect with a controlled-order fixture; log-record attribution made uniform and independent of hidden co-owners (per-record attribution, unattributed legacy lines withheld, no whole-file refusal) in FR-007 and US1.7.
+- Cross-model review round 16 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 medium, both applied: ownership filtering before tail limiting with counts over the authorized tail, and shared log rotation/retention retained as a documented effect with interleaved and forced-rotation fixtures (FR-007); the `code_execution` definition's script-enumeration wording becomes the one narrow golden exception, reworded to administrator-only enumeration (FR-012, SC-005).
+- Cross-model review round 17 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 medium, both applied: caller-kind-first superset ordering and monotone recursive provenance for cached responses with an admin-narrow-profile → child → pinned-agent fixture (FR-001); subject-bound log routing for shared-service producers (OAuth callback manager) with both interleavings tested and an SC-005 administrator exception (FR-007).
+- Cross-model review round 18 (gpt-6-astra, 2026-09-07): verdict *fix-then-plan*, 2 medium, both applied: cache provenance bound to the immutable snapshot that authorized production, with held-call narrowing fixtures (FR-001); scoring defined over the existing selected corpus (profile index or shared index with fallback) instead of "corpus-wide", with a three-scope multi-term fixture (Edge Cases, FR-005, Assumptions).
+- Cross-model review round 19 (gpt-6-astra, 2026-09-07): **VERDICT: ready-for-plan.** No findings. 19 rounds, 58 findings applied. Spec 105 is ready for `/speckit.plan`; Spec 104 (ready-for-plan at its round 14) may proceed in parallel since it declares 105 as its prerequisite.
diff --git a/specs/105-agent-scope-hardening/spec.md b/specs/105-agent-scope-hardening/spec.md
new file mode 100644
index 000000000..1eaf82ee5
--- /dev/null
+++ b/specs/105-agent-scope-hardening/spec.md
@@ -0,0 +1,217 @@
+# Feature Specification: Agent-Token Scope Hardening — Every MCP Request Authorized by Its Own Scope
+
+**Feature Branch**: `105-agent-scope-hardening`
+**Created**: 2026-09-07
+**Status**: Draft — cross-model review complete (19 rounds, gpt-6-astra, ready-for-plan 2026-09-07)
+**Input**: User description: "Agent-token scope hardening: every fixed MCP surface must authorize each request by its own token and profile scope — cached responses, set_profile and profile-URL responses, retrieve_tools metadata, direct-publication filtering, target-tier execution permission, aggregated prompts, and per-server management operations"
+
+**Related**: Spec 104 (auto routing mode — depends on this spec; its FR-016 states the invariant these corrections make true), Spec 085 (compact router, `describe_tool`), Spec 102 (schema-deferred direct mode: the publication and skew tests extended here), Spec 057 (Profiles v2), agent tokens ([docs/features/agent-tokens.md](../../docs/features/agent-tokens.md)).
+
+## Context & Motivation
+
+MCPProxy's security story is that an agent token is a *scoped* credential: it may see and use only the servers, profile and permission tiers it was granted. The cross-model review of Spec 104 verified that claim against the code one surface at a time and found eight places on the MCP surfaces where a scoped token can learn about or act on servers outside its grant. None is reachable by a token that behaves; every one is reachable by a prompt-injected or curious agent holding a legitimately narrow token. Each is a small correction; together they make the sentence "every MCP request is authorized by its own effective scope" true in every routing mode, before Spec 104 relies on it.
+
+The eight gaps, in the order a scoped agent would hit them:
+
+1. A response cached under a broad authorization can be read back under a narrower one — on the same session, another session, or through the direct call path — and pre-existing cache entries carry no authorization at all.
+2. `set_profile` answers list every configured server and enumerate every profile on an invalid selection; the profile-URL endpoint's error for a missing or deleted profile does the same, and its status codes reveal whether any profile exists.
+3. `retrieve_tools` runs and limits the search over the whole fleet before scope filtering and computes usage statistics, debug counts and session risk over the fleet, so a scoped token learns out-of-scope names and counts and loses authorized hits to hidden ones.
+4. During a direct-surface publication a returned definition can be filtered against a catalog other than the one that produced it, and names the catalog cannot parse are treated as built-ins.
+5. Retrieve-surface dispatch checks the permission of the `call_tool_*` variant the caller chose, not the tier the target tool requires, and the target-tier resolver falls back to a search that can classify the wrong tool or default to read.
+6. An aggregated prompt is authorized against a server parsed from its flattened name while its handler dispatches to the recorded owner, and unparseable names are retained rather than refused.
+7. `upstream_servers` `tail_log` and other per-server operations look up the named server before checking scope, and log-file identity is lossy (`a/b` and `a_b` share a file).
+8. Dispatch-denial and "available servers" errors name servers the caller may not see.
+
+Fix sessions for (1), (2), (5), (6) and (7) were started in parallel from the review; this spec is the acceptance contract they must satisfy, and it adds (3), (4) and (8). The round-1 review of this spec found each session's brief narrower than the contract below in at least one respect (effective-profile provenance, durable invalidation, target resolution identity, log-file identity, existence oracles); those items are marked ⚠ so the sessions can be updated.
+
+## Scope Boundary *(read before planning)*
+
+| Already exists | Reused, not rebuilt |
+|---|---|
+| Per-request agent-token context (caller kind, allowed servers, permission set, profile pin) and profile resolution (pin → URL scope → session selection → none) | the inputs to *effective authorization* |
+| Direct-surface publication order (registry, then catalog) with skew tests (Spec 102) | extended, not replaced |
+| Target-tier classification from tool annotations (used by the direct surface and code execution) | made authoritative and fail-closed |
+| Response cache with paginated, recursively cached entries | gains provenance |
+
+**Transport and caller scope.** This spec covers the HTTP MCP surfaces — `/mcp`, `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/` and the legacy aliases — for requests **authenticated as agent tokens**. Native stdio is local-administrator-only (it installs an administrator identity unconditionally and has no credential channel) and is out of scope. One narrow REST exception: the direct call path (`/api/v1/tools/call`, used by the CLI, Web UI and tray) can redeem cached responses through its `read_cache` branch; FR-001 covers that redemption door with the same effective-authorization rule — a REST caller's effective authorization is its API key or agent token **including its profile pin** (direct dispatch already enforces the pin there; a deleted pin resolves to deny-all), so a token allowing `{a,b}` but pinned to `{a}` cannot redeem an unpinned entry containing `b` through the endpoint that refuses its direct call to `b`. A pinned-token fixture compares direct dispatch and cache redemption on that endpoint. `read_cache` is not exposed on `/mcp/all`. Administrator callers (API key or local socket) keep every capability they have today. The REST management API keeps its existing policy (token server restriction without profile pin; profile listing) and is out of scope here; requests that arrive without any credential where the deployment does not require MCP authentication are administrator-shaped by that deployment's choice and are out of scope. Every correction is a deliberate change to fixed-surface runtime behaviour for agent-token callers. Administrators are affected only by the **administrator exception list**, defined once in SC-005 and referenced everywhere: legacy and internal cache entries (FR-002), exact-identity preservation including its discovery/index consequences (FR-009), withholding of definitions and prompts with no registration identity (FR-006, FR-008), and canonical container ownership and subject-bound log routing in housekeeping (FR-007). Tool-definition goldens are unchanged throughout.
+
+## Definitions *(binding)*
+
+- **Effective authorization** of a request: caller kind; the token's allowed-server set (wildcard = all); its permission set (exact membership of `read`, `write`, `destructive`); and the *effective profile scope* after resolution — token pin, else URL scope, else session selection, else none — expressed as the resulting allowed-server set and profile identity. A deleted pin resolves to deny-all, as today.
+- **Authorized population** of a request on a surface: the servers, tools and prompts its effective authorization may see under that surface's discovery predicate (availability and approval rules unchanged; retrieve discovery remains tier-blind, the direct listing tier-filtered — Spec 104 preserves this asymmetry).
+- **Registration identity** of a tool or prompt: the canonical owning server and raw upstream name recorded when it was registered on a surface, plus its tier as classified then. Never derived by parsing a flattened display name.
+- **Non-disclosing refusal**: the response for a resource outside the caller's server or profile scope is indistinguishable in status, body and timing class from the response for a nonexistent resource of the same kind. Tier denials on authorized servers are not non-disclosing by design (FR-010 precedence).
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 — A server-restricted token cannot learn about other servers (Priority: P1)
+
+A team issues an agent token restricted to server `a`. Through any route the MCP surfaces offer — cached responses, profile switching, `retrieve_tools` statistics or debug output, prompt listing, log tailing, error messages — the agent learns nothing about servers `b` or `a__b`: not their names, tool or prompt names, counts, status, logs, or existence.
+
+**Why this priority**: This is the promise the scoped-token feature makes. Each leak is small; together they let a compromised agent map the fleet.
+
+**Independent Test**: One fixture with servers `a`, `b` and `a__b`, each carrying tools, prompts, usage history and a distinctive hidden **sentinel** string in its names and descriptions; an `a`-only token; an administrator credential; and a second fixture identical except that `b` and `a__b` are absent. Every scenario runs the same request against both fixtures and asserts the `a`-only responses are equal after normalising nondeterministic fields (timestamps, cache handles, durations), and that no sentinel appears. The applicability matrix in FR-014 says which surface exposes which operation.
+
+**Acceptance Scenarios**:
+
+1. **Given** a response cached under a broader effective authorization (on the same session, another session, or produced by discovery or an upstream content block), **When** the `a`-only token redeems it through `read_cache` or the direct call path, any page or recursive child page, **Then** it receives a non-disclosing refusal.
+2. **Given** a cache entry persisted before this feature (no provenance) in an upgrade fixture, **When** any caller — administrator included — redeems it, **Then** it is refused without content and is durably invalidated (a second attempt after restart is also refused, and the store no longer holds it).
+3. **Given** the `a`-only token, **When** it calls `set_profile` with an empty selection, a selectable profile, a non-selectable profile, or a nonexistent name, **Then** the server list in the response is the effective intersection after the update, the two failing cases produce the same non-disclosing refusal, and no non-selectable profile is named.
+4. **Given** the `a`-only token's pinned profile is deleted, **When** it requests the profile URL, **Then** the status and body are the same whether or not other profiles exist and whether or not any profile is configured; the same holds for `/mcp/p` and `/mcp/p/` and for a token whose pin still exists but does not match.
+5. **Given** usage seeded on `b`, high-ranking tools on `b` for the query, and prompts on `a__b`, **When** the `a`-only token calls `retrieve_tools` with statistics and debug enabled, **Then** the response is identical between the two fixtures for every scope-independent field (usage summary, top tools, indexed counts, risk) under the retrieve oracle, and its ranked-window fields (tool set, `total`, filter diagnostics, ordering, scores) each equal the per-fixture derivation the oracle defines.
+6. **Given** prompt aggregation is on, **When** the `a`-only token lists or fetches prompts, **Then** no prompt owned by `b`, `a__b` or `__a` is listed or fetchable, and no prompt without a registration identity is listed or fetchable by anyone.
+7. **Given** the `a`-only token, **When** it calls `upstream_servers` `tail_log` (or any per-server operation it may invoke) naming `b`, `a__b`, `a/b` or `a_b`, **Then** it receives a non-disclosing refusal; and **When** an `a_b`-only token tails its own server, **Then** it receives only records attributable to `a_b` — never a line of `a/b`, never an unattributed legacy line, and never a whole-file refusal that depends on `a/b`'s presence.
+8. **Given** the `a`-only token, **When** a dispatch is denied for scope or the target server has no live client, **Then** the error names neither the canonical owner of the tool nor any server outside its authorized population.
+
+---
+
+### User Story 2 — A read-only token cannot execute above its tier (Priority: P1)
+
+A team issues a read-only agent token. The agent tries to run an approved write or destructive tool by choosing `call_tool_read`, with strict server validation on or off. Every attempt is refused because the target tool's own tier, resolved from its registration identity, decides.
+
+**Why this priority**: Permission tiers are the difference between a token that can look and a token that can delete. The direct surface already enforces this; the retrieve surface, which 92% of installs use, does not.
+
+**Independent Test**: The permission-set × target-tier × variant table of FR-009, run on the retrieve surface through `call_tool_*`, on the direct surface through direct-name dispatch, and inside a code-execution script through nested `call_tool`/`call_tools`, asserting insufficient-permission results and **zero upstream calls**.
+
+**Acceptance Scenarios**:
+
+1. **Given** a `{read}` token and an approved write tool, **When** it calls `call_tool_read` with strict validation on, **Then** the call is refused for insufficient permission and the upstream is never invoked.
+2. **Given** the same token and an approved destructive tool, **When** it calls `call_tool_read` with strict validation off, **Then** the call is refused for insufficient permission and the upstream is never invoked.
+3. **Given** a token holding the target's tier but selecting a mismatched variant, **When** it calls, **Then** the existing variant/intent mismatch handling applies unchanged.
+4. **Given** server `a` exposes a read tool `erase` and a destructive tool `ns:erase`, **When** a `{read}` token calls the latter by any route, **Then** the classification is of `ns:erase`, not `erase`, and the call is refused.
+5. **Given** a tool whose registration identity cannot be resolved (stale or missing metadata), **When** a scoped token calls it, **Then** the call is refused for insufficient permission — never authorized as read by default.
+6. **Given** a script that calls a tool above the token's tier, **When** the script completes, **Then** the nested call's refusal envelope shows insufficient permission and the script's success does not mask it.
+
+---
+
+### User Story 3 — A listing never returns a definition its own publication would not authorize (Priority: P2)
+
+Server `a`'s tool `b__c` is replaced by server `a__b`'s tool `c`, so display name `a__b__c` survives with a new owner. An `a`-only token listing tools at any moment during the publication — before, between, or after the registry and catalog switch — never receives the new owner's description or schema, in either skew direction, in full or deferred rendering. Dispatch at each seam is governed by whichever handler is registered at that moment (see scenarios 3–4).
+
+**Why this priority**: The window is short and needs a specific rename, but the disclosure is of a full definition, and the existing skew test checks names and dispatch, not the returned definition.
+
+**Independent Test**: The origin-flip fixture with a pause seam between registry and catalog publication, asserting the complete returned definition for every listing served at every seam, plus the malformed-name, built-in and tier-change cases below.
+
+**Acceptance Scenarios**:
+
+1. **Given** the origin-flip fixture, **When** the `a`-only token lists tools at any seam, **Then** each returned definition's owner and tier come from the registration identity of the publication that produced that definition.
+2. **Given** a newly registered name the catalog cannot parse (a leading `__`, or a `b__`-prefixed name absent from the old catalog), **When** it is listed, **Then** it is authorized by its own registration identity — never classified as a built-in, never withheld merely for being unparseable; built-ins are positively identified. A definition with no registration identity is withheld.
+3. **Given** a same-owner tool whose tier changes from read to destructive during publication, **When** a `{read}` token lists on the direct surface, **Then** the tool is withheld once the new tier is registered; dispatch expectations follow the **handler registered at each seam**: while the read registration is installed the call may execute, and once the destructive registration is installed it is refused for insufficient permission — no earlier revocation is required.
+4. **Given** dispatch is attempted for the flipped name at each seam, **Then** the outcome follows the registered handler: while the name is registered to authorized server `a` (before the forward flip, after the reverse flip) the call may execute; while it is registered to out-of-scope `a__b` it receives a non-disclosing refusal (the current error, which names the hidden owner, is replaced).
+
+---
+
+### Edge Cases
+
+- **Administrator callers.** Unchanged everywhere except the administrator exception list of SC-005 (legacy and internal cache entries; exact-identity preservation and its discovery/index consequences; withholding of definitions and prompts with no registration identity; canonical container ownership and subject-bound log routing in housekeeping).
+- **Unrestricted agent tokens** (no server restriction, no pin, full permission set) keep the same successes except where this spec mandates a security refusal that applies regardless of grant: (1) an **empty profile** (valid today) is refused through `set_profile` and the profile URL; (2) exact-identity policy gates (FR-009) — a config-denied or unapproved `a:ns:erase` no longer succeeds because `a:erase` is allowed, and a failed or stale identity resolution is refused; (3) definitions and prompts with no registration identity are withheld (FR-006, FR-008). Administrators keep (1); (2) and (3) apply to administrators too, as named exceptions in SC-005. Their refusal bodies change where this spec changes error shapes. Fixtures exercise (1)–(3) with an unrestricted agent and record the administrator outcome.
+- **Same-authorization cache reads** are byte-identical to today, including pagination, after nondeterministic-field normalisation.
+- **Internal cache entries** (registry and guesser caches) are not agent responses and are non-redeemable through `read_cache` by any caller.
+- **Durable invalidation.** Invalidation of a refused entry MUST survive the refusal path: the existing expiry branch deletes inside a transaction and then errors, which rolls the deletion back; the upgrade fixture asserts absence after restart.
+- **Profile selection predicate.** An unpinned token may select a profile whose server set intersects its allowed-server set; profiles with an empty intersection and nonexistent profiles are both refused identically. Profile names are therefore disclosed only for selectable profiles.
+- **URL precedence.** `set_profile` on a URL-scoped endpoint records the session selection but the URL still governs the request; the response reports the effective scope, not the stored selection alone.
+- **Ranking under scope.** Scoped discovery applies scope filtering *before* limiting. The **search corpus** is the one the existing index selection already chooses for the request: the profile-specific index when the effective profile has one (this applies to profile-scoped administrators too), otherwise the shared fleet index, with the existing fallback to the shared index when the profile index is unavailable — this selection is preserved unchanged. Scores, and therefore ordering, are computed over that selected corpus and are documented as such: a hidden tool present in the selected corpus (a token-only restriction on the shared index) can change an authorized tool's score, the order of authorized hits, and — for a multi-term query — which authorized hits survive the top-K cut; a profile-scoped request sees only its profile corpus. "Not displaced" is defined against an exhaustive search of the **selected corpus** filtered to authorized hits before taking K: the returned set equals the top-K of that filtered list. A multi-term fixture covers a profile-scoped agent, an equivalent token-only restriction on the shared index, and a profile-scoped administrator, plus the fallback case. **The retrieve oracle** (referenced by US1.5, FR-013 and SC-001). Per fixture, the expected response is derived as: the search over the selected corpus (profile index or shared index, as the existing selection chooses), filtered to authorized hits, cut to the ranked candidate window (`limit`), then passed through the existing annotation filters (`exclude_destructive` and kin) exactly as today. Cross-fixture equality excludes everything that depends on that ranked window: `score`, ordering, top-K membership, `total`, the complete `filter_diagnostics` payload (presence, counts and suggestions), the ranking-derived fields of `explain_tool` (`found_in_results`, `rank`, presence of `tool_details`), and the ranking-dependent payload consequences (truncation occurrence, retained prefix, `total_size`, pagination metadata). Each excluded field is asserted against the per-fixture derivation above. Everything else — indexed counts over the authorized population, usage summary and top tools, risk, and every scope-independent field — is compared across fixtures. A multi-term ranking-change fixture and a `limit: 1` + `exclude_destructive` fixture pin the documented effects.
+- **Retained, documented effects** that this spec does not remove: fleet-wide display-name collision admission on the direct surface (a hidden server can withhold an authorized entry); the prompt collision rule and global prompt cap; fleet-wide list-changed notifications on the fixed surfaces (Spec 104 makes them per recipient on the auto endpoint); and **shared-resource contention** — the proxy-wide call limiter is global, so a saturated limiter held by calls to a hidden server can make a call to an authorized server fail with the existing "proxy-wide limit saturated" response (a success-versus-refusal oracle that only scope-isolated admission would remove, which is out of scope). A deterministic held-call fixture (global capacity 1, no queue, a held call on hidden `b`, a call to `a`) pins the retained behaviour. Also retained: **cross-server security-scan admission** — the scan gate for a post-baseline tool addition under `trust_mode: scan` consumes other servers' tool metadata, so a same-name near-identical tool on hidden `b` can hold authorized `a`'s new tool pending (a shadowing finding), changing `a`'s discovery membership, counts and execution outcome for an `a`-only token; the approval behaviour is preserved, and this effect is excluded from the differential oracle. Fixture: real discovery with an established baseline on `a`, then an added tool that scans clean without `b` but is held with a matching peer on `b`; assert authorized ownership of everything returned and the documented approval/discovery/dispatch difference. Also retained: **shared prompt-refresh deadline** — prompt collection visits servers sequentially under one fleet-wide deadline, so a slow hidden `b` can exhaust it before authorized `a` is visited and `a`'s approved prompts drop out of the published set until the next refresh; the effect is documented, excluded from the differential oracle, and pinned by a controlled-order fixture (hidden `b` consuming the deadline; `a`'s prompt absent from list/get; no hidden content). Also retained: **shared log rotation and retention** for colliding server names (FR-007) — attribution filters what is returned, not what history survives rotation. The invariant in FR-012 is stated with these named.
+- **Upstream text.** Authorized upstream content that happens to mention another server's name is not scrubbed; the guarantee is about proxy-produced data, not semantic filtering of authorized responses.
+- **Operator-published content.** Two kinds of operator-authored content are published to every caller by design and sit outside the semantic-disclosure guarantee: (1) custom initialization `instructions` (Spec 104 FR-019 preserves them on every rung); (2) stored code-execution scripts — their names and any constants they return without an upstream call. Documentation MUST warn operators not to place server names or secrets in either. What the guarantee does cover: a missing-script error MUST NOT enumerate other script names or the script count to an agent-token caller (non-disclosing refusal), while administrators keep today's enumeration; and every upstream call a script makes remains scope-checked (FR-009). Because the published `code_execution` definition currently tells callers to discover scripts by requesting a nonexistent name, that definition text MUST be corrected to say enumeration is administrator-only and agent-token callers must already know the script name — the one **narrow golden exception** in this spec (FR-012): the affected description strings change, nothing else in the goldens does, and both caller kinds are tested. Fixtures: a scoped initialization with instructions mentioning `b:private_search` (published, documented), a missing-script request under a restricted token (no enumeration), and a script returning a constant (published, documented) while its nested call to `b` is refused.
+- **Case-insensitive filesystems.** Log-file identity handling is tested with names differing only in case.
+- **Prompt refresh interleaving.** Prompt sets are installed per surface instance in sequence, and approval-triggered refreshes can overlap event-triggered ones; ownership is bound to the accepted registration the handler dispatches to, so an interleaving cannot authorize against a stale owner.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+- **FR-001** *(cached responses)* ⚠: A cached response MUST carry the **same immutable authorization snapshot that authorized producing it** — resolved once at dispatch authorization and carried to the cache write, never re-resolved from mutable profile or session state at response completion (fixtures: a held call to `b` under profile `{a,b}` while the session selection, and separately the profile definition, is narrowed to `{a}` before the response completes; the entry is stamped `{a,b}` and is not redeemable under `{a}` on MCP or REST). That snapshot is the producing request's **effective authorization** (Definitions), and every redemption door — `read_cache` on any MCP surface, the REST direct call path's cache branch (Scope Boundary exception), and recursive child pages — MUST refuse a request whose current effective authorization is neither equal to nor a superset of the snapshot. Superset is ordered by **caller kind first**: an administrator qualifies for any snapshot; an agent token never qualifies for an administrator-produced snapshot; between agent snapshots, allowed-server set, permission set and effective profile scope must each contain the snapshot's. **Recursive provenance is monotone**: a page produced by redeeming a parent entry carries the *parent's* snapshot (or, if the redeemer's authorization is narrower, the narrower one), never a snapshot broader than the parent's — so an administrator with a narrow session profile redeeming a broad entry cannot mint a child that a pinned agent could later redeem. Fixture: administrator with session profile `{a}` redeems an entry containing `b`, the recursive child is then requested by a wildcard full-permission agent pinned to `{a}` — refused, on MCP and on the REST direct call path. Refusal is non-disclosing.
+- **FR-002** *(legacy and internal entries)*: Entries with absent, legacy or unrecognised provenance — including every entry persisted before this feature — MUST be refused for every caller and durably invalidated on first redemption; internal registry and guesser cache entries MUST be non-redeemable. An upgrade fixture with a pre-feature record MUST assert refusal, absence after restart, and no content in the response.
+- **FR-003** *(`set_profile`)* ⚠: The server list in a `set_profile` response MUST be the effective intersection after the update (token restriction ∩ effective profile, with URL scope still governing where present); an unpinned token may select only profiles whose server set intersects its allowed servers; non-selectable and nonexistent profiles MUST produce the same non-disclosing refusal, and no non-selectable profile is ever named. `active_profile` reports the stored session selection; the server list reports effective scope.
+- **FR-004** *(profile URL)*: The profile-URL endpoint MUST apply the same selectable-profile predicate as FR-003: an unpinned token may initialize through a profile URL only if that profile's server set intersects its allowed servers. Its agent-facing status and body MUST be identical across "profile missing", "profile deleted", "profile exists but is not selectable" (empty intersection, empty profile, or empty server grant), "pin mismatch", "no profiles configured" and "other profiles exist" — pin mismatch evaluated independently of fleet population — for `/mcp/p/`, `/mcp/p` and `/mcp/p/`. Tests initialize through a selectable and a non-selectable existing profile URL with an unpinned restricted token.
+- **FR-005** *(`retrieve_tools`)*: Scoped discovery MUST apply scope filtering before result limiting; indexed counts MUST be computed over the authorized population, and `total` and filter diagnostics over the authorized ranked candidate window (as today, but with only authorized candidates in that window); usage ranking MUST be computed over the authorized population's approved tools (stale history for hidden or removed tools excluded) before the top-N cut; session risk MUST be computed over the authorized servers' tools under the existing availability rules, tier-blind; `include_disabled` and `explain_tool` follow the same population (caller-supplied names echoed by `explain_tool` are not disclosure). Scoring over the existing selected corpus (profile index or shared index) is retained and documented.
+- **FR-006** *(aggregated prompts)*: A prompt MUST be authorized for listing and fetching against the registration identity the handler dispatches to. Because that identity records the owner at registration, an unparseable **display name** (an owner beginning with `__`, which is a valid server name today) is not unknown ownership: the prompt is authorized normally for callers who may see that owner and withheld from others. Ownership is unknown only when no registration identity exists (an empty upstream prompt name, or a display entry with no accepted registration); such prompts MUST be withheld and unfetchable (fail closed). Fixture: server `__a` with prompt `review` is listed and fetchable by an unrestricted agent and by administrators, and withheld from an `a`-only token. Tests cover authenticated `prompts/list` and `prompts/get`, malformed names, collisions in both input orders, retained old registrations, and overlapping refreshes.
+- **FR-007** *(per-server operations)* ⚠: Every server-management operation that names a server MUST authorize the name against the caller's effective authorization before lookup, with non-disclosing refusal. Log tailing MUST additionally establish canonical ownership of the log resource: where two server names map to one log file, the reader MUST return only records attributable to the authorized server (each record carries its writer's canonical server identity; records without one are non-attributable). The policy is **uniform and independent of hidden co-owners**: a scoped caller never receives a whole-file refusal that depends on whether another server shares the file — it receives exactly the records attributable to its own server, and legacy records with no attribution are withheld, whether or not a co-owner exists. Ownership filtering MUST precede tail limiting, and `lines_returned` MUST count the authorized tail, so an interleaved foreign line never displaces an authorized one from the returned window. Shared-file **rotation and retention** remain shared (isolating them per owner is out of scope): a hidden co-owner's output can rotate an authorized record out of the readable history, so this is a retained, documented effect excluded from the differential oracle. Fixtures: an `a_b`-only token tailing with and without hidden `a/b` present, with interleaved lines, receives the same attributable records within the retained history and no foreign or unattributed record; a forced-rotation fixture pins the documented eviction difference. Tests include `a/b` vs `a_b` and case-only differences. Attribution MUST be **subject-bound for shared-service producers**: a component serving several servers (the OAuth callback manager, and any similar shared service) MUST write each record through the logger of the server that record concerns — callback shutdown uses the target callback server's recorded logger, never whichever server's logger was installed last — so no server's name, port or flow state is written into another server's log; legacy records whose stamped identity conflicts with their subject are withheld from scoped callers. Fixture: start hidden `b`'s OAuth flow, start `a`'s, complete `b`, then the reverse interleaving, with distinct log files; `a`'s tail contains no `b` metadata in either order. The resulting log-routing change is administrator-visible and is listed in SC-005. Ownership MUST also hold for the **container resources** proxy housekeeping references: Docker cleanup for server `a` MUST match only containers canonically owned by `a` (never `a-b`'s by name prefix), so no foreign container name or id is ever written into `a`'s log; legacy foreign-container records already present in a log are treated as non-attributable and withheld from scoped callers. Fixture: `a` and hidden `a-b` with distinct log files, cleanup run, `a`'s tail contains no `a-b` container name or id.
+- **FR-008** *(direct publication)*: Each definition returned by direct-surface discovery MUST take its owner and tier from its own registration identity in the publication that produced it, at every seam of the publication and in both skew directions, in full and deferred rendering. A definition is withheld only when it lacks a valid registration identity — never merely because its display name is unparseable or absent from the previous catalog (server `__a`'s tool has a recorded owner and tier and is authorized normally). Built-ins are positively identified, never inferred from a parse failure. Fixture: direct tool on server `__a` — listed, describable and dispatchable for an unrestricted agent and administrators; refused to an `a`-only token.
+- **FR-009** *(target-tier execution)* ⚠: On every dispatch path (`call_tool_*`, direct-name dispatch, nested script calls), authorization MUST resolve the target's registration identity from exactly the canonical server / raw tool pair that will be dispatched, and every policy gate — tier classification, configured tool denial, approval and callability — MUST be evaluated on that same pair (never on a name with a namespace prefix stripped); tests cover same-tier paired names (`erase` approved, `ns:erase` config-denied or unapproved) through retrieve and nested dispatch with zero upstream calls. Identity MUST be preserved end to end: approval-record creation, baseline capture, index updates and direct publication MUST record and look up the same canonical server / raw name pair as discovery and dispatch — a namespaced tool never collapses to its suffix at any stage, so a pending approval for `ns:erase` is a pending approval for `ns:erase`, and "no record found" is never classified as callable for a tool the discovery snapshot contains. Legacy approval records whose identity was collapsed (a record for `erase` on a server whose snapshot also holds `ns:erase`) are treated conservatively: they approve only the exact raw name they store, and the namespaced tool remains pending until approved by its own name. Fixture: run real discovery and approval processing on a manual-trust server whose baseline exists, then add read-tier `ns:erase`; assert it is pending under its own name and that direct, retrieve and nested dispatch all refuse it with zero upstream calls. It MUST classify the tier from that identity, and require the caller's permission set to contain that tier **in addition to** the existing variant check. A known tool with no annotations is classified by the existing annotation-defaulting rule and that rule is documented; a failed or stale resolution MUST refuse scoped callers. Acceptance tables: (a) retrieve dispatch — permission sets `{read}`, `{read,write}`, `{read,write,destructive}` × target tiers read/write/destructive × variants read/write/destructive × strict validation on/off; (b) direct-name dispatch and nested script dispatch — permission sets × target tiers only (no variant exists there). Cells are classified before the run, in this order: *permission-disallowed* (the caller's set lacks the target tier **or**, on retrieve dispatch, lacks the selected variant's tier — e.g. `{read}` calling a read target through `call_tool_destructive`) → refused for insufficient permission; then, among cells passing both permission checks, *intent-mismatch* (the variant disagrees with the target tier under the existing strict-validation predicate) → refused by the existing mismatch handling; the remainder → *allowed* and dispatched. Every refused cell asserts zero upstream calls; the two refusal kinds are asserted with their own oracles.
+- **FR-010** *(refusal shapes)*: Refusal precedence, evaluated in this order: (1) a resource on a server or profile outside the caller's effective scope → **non-disclosing** refusal (indistinguishable from nonexistent), on every surface and mode; (2) a resource on an **authorized** server that the caller may not execute because of its tier → an **insufficient-permission** refusal on every dispatch path, including the direct surface where the over-tier tool is withheld from the listing (tier denial on an authorized server is not a scope leak: the caller may already discover that tool on the retrieve surface); (3) other refusals unchanged. Dispatch denial for scope MUST NOT name the canonical owner; "available servers" suggestions MUST be limited to the authorized population. `describe_tool` MUST produce its not-found response — including any case-correction suggestion — through one policy evaluated over the **authorized** corpus only, so an unauthorized existing id and a nonexistent id yield the same response (a hidden exact match with an authorized case-equivalent alternative gets the same suggestion as a nonexistent id would). Tests cover hidden `b:read` vs authorized `B:read` on both the indexed and the direct surface. On the direct surface, agent-facing resolution of both display names and canonical ids — including alias admission and precedence between a hidden display entry and an authorized canonical alias — MUST be computed over the **authorized corpus**, so an id that resolves to an authorized tool when a hidden server is absent resolves the same way when it is present (cross-namespace fixture: authorized `x__y` exposing `z` vs hidden `x` exposing `y:z`, in definition and check modes; administrator resolution unchanged and tested separately).
+- **FR-011** *(performance)*: Measured on the frozen 527-tool snapshot with a frozen prompt set (50 prompts) and a frozen 10-page cache entry, 200 calls after 20 warm-up calls, on the CI reference runner against the merge-base revision: administrator p95 for `retrieve_tools`, `read_cache`, `prompts/list` and `tools/list` MUST regress by no more than 10% or 5 ms, whichever is larger; scoped-caller p95 MUST be within 20 ms of the administrator figure.
+- **FR-012** *(compatibility and documentation)*: These corrections apply on the MCP surfaces in every routing mode for agent-token callers (and to administrators only per the SC-005 administrator exception list); tool-definition goldens are unchanged and MUST pass unregenerated, with one narrow exception: the `code_execution` description and `script` parameter text that advertise script enumeration by failed call are reworded to administrator-only enumeration (Edge Cases, Operator-published content), and only those strings may differ in the regenerated goldens; runtime refusal bodies change as specified. The agent-token documentation MUST state the invariant — "a request authenticated as an agent token on an HTTP MCP surface cannot learn about or act on servers outside its effective authorization through proxy-produced data" — and list the covered surfaces, the retained effects from Edge Cases, and the two operator-published content kinds (custom instructions, stored scripts) with the warning not to place server names or secrets in them.
+- **FR-013** *(regression suite)*: The scenarios above MUST exist as automated tests in the server test suite, using the two-fixture differential oracle with sentinels and nondeterministic-field normalisation (the retrieve oracle of Edge Cases and the retained-admission exclusions of SC-001); each fix delivered by a parallel session MUST be accepted only when the corresponding tests pass.
+- **FR-014** *(applicability matrix)*: Tests MUST follow this matrix and assert that unavailable operations stay unavailable:
+
+ | Operation | retrieve (`/mcp`, `/mcp/call`) | direct (`/mcp/all`) | code (`/mcp/code`) |
+ |---|---|---|---|
+ | `read_cache` | yes | n/a | n/a |
+ | `set_profile` | yes | n/a | yes |
+ | `retrieve_tools` metadata | yes | n/a | yes (no `detail`) |
+ | prompts list/get | yes | yes | yes |
+ | `tail_log` / per-server ops | yes | n/a | yes |
+ | `describe_tool` (definition mode, incl. case suggestions) | yes | yes | n/a |
+ | stored-script resolution (missing-name refusal) | yes (when code execution is enabled) | n/a | yes |
+ | execution tier | `call_tool_*` | direct-name dispatch | nested `call_tool`/`call_tools` |
+ | publication filtering | n/a | yes | n/a |
+
+### Key Entities
+
+- **Effective authorization snapshot**: the request-derived provenance stored with a cached response and compared on redemption (FR-001).
+- **Registration identity**: the owner, raw name and tier recorded at registration for a tool or prompt on a surface; the sole source of ownership and tier for filtering, listing and dispatch (FR-006, FR-008, FR-009).
+- **Authorized population**: the per-request set every count, ranking, risk figure and suggestion is computed over (FR-005, FR-010).
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: For every User Story 1 scenario on every applicable surface, the `a`-only token's normalised response is identical between the three-server fixture and the `a`-only fixture — excluding the retrieve-oracle fields (Edge Cases: ranking and ranking-dependent payload fields, checked per fixture) and the retained effects (prompt-name collision, global prompt cap, direct display-name collision, shared-limiter contention, cross-server scan admission, shared prompt-refresh deadline, shared log rotation and retention), whose fixtures instead assert authorized ownership of everything returned, absence of hidden definitions and content, and the documented outcome — and contains no sentinel.
+- **SC-002**: In the FR-009 tables, 100% of permission-disallowed cells are refused for insufficient permission and 100% of intent-mismatch cells by the existing mismatch handling, each with zero upstream calls, on the dispatch paths where the cell exists; the paired-name case (`erase` vs `ns:erase`) and the unresolvable-identity case are refused.
+- **SC-003**: The origin-flip fixture returns zero unauthorized definitions across every listing at every seam, both skew directions, full and deferred; definitions without a valid registration identity are withheld from every caller; valid unparseable-display definitions (server `__a`) are returned only to callers authorized for that owner; built-ins are positively identified.
+- **SC-004**: The upgrade fixture's pre-feature cache record is refused for administrator and agent callers, absent after restart, and returns no content.
+- **SC-005**: Administrator responses on every surface are identical before and after the feature for the same fixture after nondeterministic-field normalisation, except the named administrator exceptions: FR-002 (legacy cache entries, **and** internal registry/guesser cache entries generated after the upgrade, which administrators can redeem today and may not afterwards — tested separately from the legacy fixture with a freshly generated internal registry entry); FR-009 exact-identity preservation — both its policy-gate outcomes (a config-denied `a:ns:erase` is refused for administrators too) and its discovery consequences (`erase` and `ns:erase` become distinct index entries, so administrator search membership, counts and scores change for fixtures containing such pairs — a positive fixture with both approved asserts both identities survive discovery and indexing, while unaffected fixtures keep response parity); the withholding of prompts and definitions with no registration identity (an empty upstream prompt name `a:` registered as `a__` is no longer listed for anyone — fixture with an explicit administrator outcome); and FR-007's canonical container ownership and subject-bound log routing for shared-service producers, whose housekeeping outcomes and resulting log and status records change for administrators too (the `a` vs `a-b` and OAuth-interleaving fixtures record the administrator outcome instead of requiring pre-feature parity); all tool-definition goldens pass unregenerated except the `code_execution` enumeration wording named in FR-012, whose regenerated diff is limited to those strings.
+- **SC-006**: FR-011's latency bounds hold.
+- **SC-007**: The regression suite of FR-013 covers every acceptance scenario in this spec by name, and each of the five parallel fix branches is accepted only against it.
+
+## Assumptions
+
+- **Non-disclosing refusal** is the chosen strategy, matching the entitlement pattern already used for hidden REST resources (status parity with an absent resource, never "body must not contain the name").
+- **Superset redemption** (FR-001) is safe because a broader authorization could have produced the entry itself; equality-only would break administrators reading agent-produced entries.
+- **Profile selection intersects** rather than being public: this narrows what unpinned tokens can see and select compared with today, deliberately.
+- **Selected-corpus scores** are retained: profile-specific indexes already exist and are used as today; token-only restrictions search the shared index, and adding per-token indexes is out of scope. The result-set stability guarantee is what matters.
+- **Strict server validation** is one boolean; the table tests both values and introduces no third mode.
+- **Parallel sessions** implementing (1), (2), (5), (6), (7) were briefed before this contract existed; the ⚠ marks name where their briefs are narrower.
+
+## Out of Scope
+
+- The REST management API's scope policy and profile listing; native stdio (administrator-only by construction).
+- Deployments that allow unauthenticated MCP requests.
+- Changing which quarantined, pending or disabled tools each surface shows, or the retrieve/direct tier asymmetry.
+- Per-recipient list-changed notifications, collision admission, and the prompt cap (retained; notifications addressed for the auto endpoint in Spec 104).
+- New token capabilities or a new authorization model; scope-local search scoring.
+
+## Commit Message Conventions *(mandatory)*
+
+When committing changes for this feature, follow these guidelines:
+
+### Issue References
+- ✅ **Use**: `Related #[issue-number]` - Links the commit to the issue without auto-closing
+- ❌ **Do NOT use**: `Fixes #[issue-number]`, `Closes #[issue-number]`, `Resolves #[issue-number]` - These auto-close issues on merge
+
+**Rationale**: Issues should only be closed manually after verification and testing in production, not automatically on merge.
+
+### Co-Authorship
+- ❌ **Do NOT include**: `Co-Authored-By: Claude `
+- ❌ **Do NOT include**: "🤖 Generated with [Claude Code](https://claude.com/claude-code)"
+
+**Rationale**: Commit authorship should reflect the human contributors, not the AI tools used.
+
+### Example Commit Message
+```
+feat: [brief description of change]
+
+Related #[issue-number]
+
+[Detailed description of what was changed and why]
+
+## Changes
+- [Bulleted list of key changes]
+- [Each change on a new line]
+
+## Testing
+- [Test results summary]
+- [Key test scenarios covered]
+```
diff --git a/specs/README.md b/specs/README.md
index 5f2c644a0..e622c786e 100644
--- a/specs/README.md
+++ b/specs/README.md
@@ -80,6 +80,8 @@ Brainstormed design docs that feed future specs live under [`docs/superpowers/sp
| [041-quarantine-invariants](./041-quarantine-invariants/) | Quarantine State Machine Invariants & Property Tests | — | — |
| [042-telemetry-tier2](./042-telemetry-tier2/) | Telemetry Tier 2 — Privacy-Respecting Usage Signals | `drafted` | 0/91 (0%) |
| [043-linux-package-repos](./043-linux-package-repos/) | Linux Package Repositories (apt/yum) | `shipped` | 39/41 (95%) |
+| [104-auto-routing-mode](./104-auto-routing-mode/) | Auto Routing Mode — Budget-Fitted Tool Surface Per Session | `drafted` | — |
+| [105-agent-scope-hardening](./105-agent-scope-hardening/) | Agent-Token Scope Hardening — Every MCP Request Authorized by Its Own Scope | `drafted` | — |
## Updating this index