From 5485b8bc66b2be6285d711cfba06855fa49a853e Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 12 Oct 2026 05:33:33 +0000 Subject: [PATCH 01/11] chore(specs): gardener checkbox sync --- specs/113-upstream-resilience/tasks.md | 80 +++++++++++++------------- 1 file changed, 40 insertions(+), 40 deletions(-) diff --git a/specs/113-upstream-resilience/tasks.md b/specs/113-upstream-resilience/tasks.md index 4eec10b78..ab269a07c 100644 --- a/specs/113-upstream-resilience/tasks.md +++ b/specs/113-upstream-resilience/tasks.md @@ -10,25 +10,25 @@ Format: `[ID] [P?] [Story] Description (files) — FR`. `[P]` = can run in paral ## Slice 113-a — oauth-refresh-robustness (US1, G1+G2) — T100–T129 -- [ ] T100 [P] [US1] Failing test: `ClassifyRefreshError` table — `OAuthError{invalid_grant}` wrapped by mcp-go (`%w`), 200-with-error-body form, `invalid_client`, `unauthorized_client`, `unsupported_grant_type`, `invalid_scope`, mcp-go `"refresh token request failed with status 503: "`, 429, `*net.OpError` dial/reset, `context.DeadlineExceeded`, `server not found`, `server does not use OAuth`, unknown; plus the manual-path typed error (`internal/oauth/refresh_errors_test.go`) — FR-007, FR-008 -- [ ] T101 [US1] Implement `ClassifyRefreshError` + `RefreshHTTPError`; derive the existing metric labels from it; keep the substring list only as the last fallback (`internal/oauth/refresh_errors.go`, `refresh_manager.go`) — FR-007, FR-008 -- [ ] T102 [P] [US1] Failing test: storage `UpdateOAuthToken(key, mutate)` preserves `ClientID/ClientSecret/CallbackPort/RedirectURI/Created/DisplayName` when `UpdateOAuthClientCredentials` runs concurrently (100 interleaved goroutines, `-race`) (`internal/storage/bbolt_oauth_update_test.go`) — FR-006 -- [ ] T103 [US1] Implement `BoltDB.UpdateOAuthToken`; switch `PersistentTokenStore.SaveToken` and the manual refresh path to it (`internal/storage/bbolt.go`, `internal/oauth/persistent_token_store.go`, `internal/upstream/core/client.go`) — FR-006 -- [ ] T104 [P] [US1] Failing test: coordinator — N=50 barrier-started `Do` calls on one key run `fn` once and all get the same token; a caller whose observed RT is stale gets the persisted token with `skipped=true` and no `fn` call; a failing `fn` returns the same error to all waiters; a cancelled initiator does not cancel the flight; different keys run in parallel (`internal/oauth/refresh_coordinator_test.go`) — FR-001, FR-003, FR-004 -- [ ] T105 [US1] Implement `RefreshCoordinator` (`internal/oauth/refresh_coordinator.go`) — FR-001, FR-003, FR-004, FR-011 -- [ ] T106 [P] [US1] Failing test: `PersistentTokenStore.GetToken` with a bound refresher and an expired token refreshes through the coordinator and returns the new token; without a bound refresher it never calls the network (assert on an `httptest` AS request counter); terminal error wraps `transport.ErrOAuthAuthorizationRequired`; transient returns `ErrTokenRefreshTransient` (`internal/oauth/persistent_token_store_test.go`) — FR-002, FR-005 -- [ ] T107 [US1] Implement refresher binding: `SetRefresher`/`BindRefreshHandler` with an `atomic.Pointer` handler slot; `GetToken` pre-emption; `SaveToken` never enters the coordinator (`internal/oauth/persistent_token_store.go`, `internal/oauth/config.go` attach, `internal/upstream/core/connection_oauth.go` bind call) — FR-002, FR-005 -- [ ] T108 [US1] Route `RefreshOAuthTokenDirect` (both sub-paths) through the coordinator with trigger `proactive`; manual path returns `RefreshHTTPError` (`internal/upstream/core/client.go`, `internal/upstream/manager.go`) — FR-001, FR-007 -- [ ] T109 [P] [US1] Failing test (SC-001): rotating `httptest` AS that revokes the grant on refresh-token reuse; expired token; 50 goroutines through a real mcp-go `StreamableHTTP` client with OAuth against an `httptest` MCP server + 1 concurrent `RefreshOAuthTokenDirect`; assert exactly 1 token request, all calls succeed; `-race -count=20` (`internal/upstream/core/oauth_refresh_race_test.go`) — FR-012, SC-001 -- [ ] T110 [P] [US1] Failing test: `invalid_client` with a DCR record → `ClearOAuthClientCredentials` called once, schedule `RefreshStateFailed` with the re-register message, zero further retries; second `invalid_client` after a re-registration and before any success → terminal "rejects new registrations"; static client → terminal, credentials untouched; a registration or grant saved by a concurrent login is not cleared (compare-and-clear) (`internal/oauth/refresh_manager_invalid_client_test.go`) — FR-009, SC-002 -- [ ] T111 [US1] Implement `invalid_client` handling and per-key re-registration state (`internal/oauth/refresh_manager.go`, `refresh_coordinator.go`) — FR-009 -- [ ] T112 [P] [US1] Failing test: `RefreshManager` reads records by server key (token-age log and `EmitOAuthTokenRefreshed` fire for a keyed record) (`internal/oauth/refresh_manager_test.go`) — FR-010 -- [ ] T113 [US1] Fix the two `GetOAuthToken(serverName)` lookups to use the server key (needs the server URL: obtain via the runtime interface or store the key on the schedule) (`internal/oauth/refresh_manager.go`) — FR-010 -- [ ] T114 [US1] CLI in-memory store path uses the same coordinator (`internal/oauth/config.go` `globalTokenStoreManager`) + test — FR-014 -- [ ] T119 [P] [US1] Failing test: bound store returns `ExpiresAt` zero to mcp-go and mcp-go never issues a refresh even when the token expires between `GetToken` and `IsExpired`; reactive refresh with a DCR record and a handler lacking a client id uses stored credentials; terminal latch (no network after `invalid_grant` until a new token is saved) and transient cooldown; compare-and-clear does not clear a registration saved by a concurrent login; login-flow `invalid_client` after re-registration is terminal (`internal/oauth/refresh_coordinator_test.go`, `internal/upstream/core/oauth_refresh_race_test.go`) — FR-002, FR-003, FR-004, FR-009 -- [ ] T120 [P] [US1] Failing test: login saves a new token and DCR client while an old refresh flight is in flight; the old flight's success is discarded (login token kept, client/token pair consistent) and its `invalid_grant` failure neither latches nor fails the schedule (`internal/oauth/refresh_coordinator_test.go`) — FR-006a +- [x] T100 [P] [US1] Failing test: `ClassifyRefreshError` table — `OAuthError{invalid_grant}` wrapped by mcp-go (`%w`), 200-with-error-body form, `invalid_client`, `unauthorized_client`, `unsupported_grant_type`, `invalid_scope`, mcp-go `"refresh token request failed with status 503: "`, 429, `*net.OpError` dial/reset, `context.DeadlineExceeded`, `server not found`, `server does not use OAuth`, unknown; plus the manual-path typed error (`internal/oauth/refresh_errors_test.go`) — FR-007, FR-008 +- [x] T101 [US1] Implement `ClassifyRefreshError` + `RefreshHTTPError`; derive the existing metric labels from it; keep the substring list only as the last fallback (`internal/oauth/refresh_errors.go`, `refresh_manager.go`) — FR-007, FR-008 +- [x] T102 [P] [US1] Failing test: storage `UpdateOAuthToken(key, mutate)` preserves `ClientID/ClientSecret/CallbackPort/RedirectURI/Created/DisplayName` when `UpdateOAuthClientCredentials` runs concurrently (100 interleaved goroutines, `-race`) (`internal/storage/bbolt_oauth_update_test.go`) — FR-006 +- [x] T103 [US1] Implement `BoltDB.UpdateOAuthToken`; switch `PersistentTokenStore.SaveToken` and the manual refresh path to it (`internal/storage/bbolt.go`, `internal/oauth/persistent_token_store.go`, `internal/upstream/core/client.go`) — FR-006 +- [x] T104 [P] [US1] Failing test: coordinator — N=50 barrier-started `Do` calls on one key run `fn` once and all get the same token; a caller whose observed RT is stale gets the persisted token with `skipped=true` and no `fn` call; a failing `fn` returns the same error to all waiters; a cancelled initiator does not cancel the flight; different keys run in parallel (`internal/oauth/refresh_coordinator_test.go`) — FR-001, FR-003, FR-004 +- [x] T105 [US1] Implement `RefreshCoordinator` (`internal/oauth/refresh_coordinator.go`) — FR-001, FR-003, FR-004, FR-011 +- [x] T106 [P] [US1] Failing test: `PersistentTokenStore.GetToken` with a bound refresher and an expired token refreshes through the coordinator and returns the new token; without a bound refresher it never calls the network (assert on an `httptest` AS request counter); terminal error wraps `transport.ErrOAuthAuthorizationRequired`; transient returns `ErrTokenRefreshTransient` (`internal/oauth/persistent_token_store_test.go`) — FR-002, FR-005 +- [x] T107 [US1] Implement refresher binding: `SetRefresher`/`BindRefreshHandler` with an `atomic.Pointer` handler slot; `GetToken` pre-emption; `SaveToken` never enters the coordinator (`internal/oauth/persistent_token_store.go`, `internal/oauth/config.go` attach, `internal/upstream/core/connection_oauth.go` bind call) — FR-002, FR-005 +- [x] T108 [US1] Route `RefreshOAuthTokenDirect` (both sub-paths) through the coordinator with trigger `proactive`; manual path returns `RefreshHTTPError` (`internal/upstream/core/client.go`, `internal/upstream/manager.go`) — FR-001, FR-007 +- [x] T109 [P] [US1] Failing test (SC-001): rotating `httptest` AS that revokes the grant on refresh-token reuse; expired token; 50 goroutines through a real mcp-go `StreamableHTTP` client with OAuth against an `httptest` MCP server + 1 concurrent `RefreshOAuthTokenDirect`; assert exactly 1 token request, all calls succeed; `-race -count=20` (`internal/upstream/core/oauth_refresh_race_test.go`) — FR-012, SC-001 +- [x] T110 [P] [US1] Failing test: `invalid_client` with a DCR record → `ClearOAuthClientCredentials` called once, schedule `RefreshStateFailed` with the re-register message, zero further retries; second `invalid_client` after a re-registration and before any success → terminal "rejects new registrations"; static client → terminal, credentials untouched; a registration or grant saved by a concurrent login is not cleared (compare-and-clear) (`internal/oauth/refresh_manager_invalid_client_test.go`) — FR-009, SC-002 +- [x] T111 [US1] Implement `invalid_client` handling and per-key re-registration state (`internal/oauth/refresh_manager.go`, `refresh_coordinator.go`) — FR-009 +- [x] T112 [P] [US1] Failing test: `RefreshManager` reads records by server key (token-age log and `EmitOAuthTokenRefreshed` fire for a keyed record) (`internal/oauth/refresh_manager_test.go`) — FR-010 +- [x] T113 [US1] Fix the two `GetOAuthToken(serverName)` lookups to use the server key (needs the server URL: obtain via the runtime interface or store the key on the schedule) (`internal/oauth/refresh_manager.go`) — FR-010 +- [x] T114 [US1] CLI in-memory store path uses the same coordinator (`internal/oauth/config.go` `globalTokenStoreManager`) + test — FR-014 +- [x] T119 [P] [US1] Failing test: bound store returns `ExpiresAt` zero to mcp-go and mcp-go never issues a refresh even when the token expires between `GetToken` and `IsExpired`; reactive refresh with a DCR record and a handler lacking a client id uses stored credentials; terminal latch (no network after `invalid_grant` until a new token is saved) and transient cooldown; compare-and-clear does not clear a registration saved by a concurrent login; login-flow `invalid_client` after re-registration is terminal (`internal/oauth/refresh_coordinator_test.go`, `internal/upstream/core/oauth_refresh_race_test.go`) — FR-002, FR-003, FR-004, FR-009 +- [x] T120 [P] [US1] Failing test: login saves a new token and DCR client while an old refresh flight is in flight; the old flight's success is discarded (login token kept, client/token pair consistent) and its `invalid_grant` failure neither latches nor fails the schedule (`internal/oauth/refresh_coordinator_test.go`) — FR-006a - [ ] T115 [US1] 5xx/429/network → existing backoff with `failed_server_error`/`failed_network` labels; test asserts backoff sequence unchanged — FR-008, FR-013 -- [ ] T116 Docs: `docs/oauth-resource-autodetect.md` or the OAuth troubleshooting page — refresh serialization, `invalid_client` behaviour, new metric labels (published-site rules apply) +- [x] T116 Docs: `docs/oauth-resource-autodetect.md` or the OAuth troubleshooting page — refresh serialization, `invalid_client` behaviour, new metric labels (published-site rules apply) - [ ] T117 Gates: race tests, server-tag tests (CI skip regex), golangci-lint v2 ×2, `./scripts/test-api-e2e.sh` (isolated instance) - [ ] T118 Cross-model review (opencode harness, gpt-6.1-sol), ≤10 rounds - T121–T129 reserved for 113-a follow-ups @@ -36,40 +36,40 @@ Format: `[ID] [P?] [Story] Description (files) — FR`. `[P]` = can run in paral ## Slice 113-b — oauth-discovery-overrides (US2, G3+G5) — T130–T159 - [ ] T130 [P] [US2] Failing test: `OAuthConfig` new fields JSON/mapstructure round-trip, `OAuthConfigChanged` detects each, `MergeOAuthConfig` merges each, storage `UpstreamRecord` round-trip (`internal/config/*_test.go`, `internal/storage/*_test.go`) — FR-022, FR-028, FR-029 -- [ ] T131 [US2] Add the four fields; update `OAuthConfigChanged`, `MergeOAuthConfig`, `copyOAuthConfig` (`internal/config/config.go`, `merge.go`) — FR-022, FR-028 -- [ ] T132 [P] [US2] Failing test: validation table — https ok; http loopback (`localhost`, `127.0.0.5`, `[::1]`) ok; http public host rejected; relative, fragment, userinfo, empty host rejected; load path drops invalid with Warn and boot succeeds (`internal/config/oauth_validation_test.go`) — FR-023 -- [ ] T133 [US2] Implement write-time validation (`ValidateDetailed`, REST, MCP `upstream_servers`, CLI) and load-time sanitize (`internal/config/oauth_validation.go`, write paths) — FR-023 -- [ ] T134 [P] [US2] Failing test: `OAuthTransportWrapper` rewrites AS metadata fields from overrides, output passes mcp-go URL validation; synthesizes a document when metadata is unreachable and authz+token overrides exist; leaves non-metadata responses untouched (`internal/oauth/transport_wrapper_test.go`) — FR-024 -- [ ] T135 [US2] Implement metadata rewrite/synthesis in the wrapper; pass `auth_server_metadata_url` to `OAuthConfig.AuthServerMetadataURL` (`internal/oauth/transport_wrapper.go`, `internal/oauth/config.go`) — FR-024 +- [x] T131 [US2] Add the four fields; update `OAuthConfigChanged`, `MergeOAuthConfig`, `copyOAuthConfig` (`internal/config/config.go`, `merge.go`) — FR-022, FR-028 +- [x] T132 [P] [US2] Failing test: validation table — https ok; http loopback (`localhost`, `127.0.0.5`, `[::1]`) ok; http public host rejected; relative, fragment, userinfo, empty host rejected; load path drops invalid with Warn and boot succeeds (`internal/config/oauth_validation_test.go`) — FR-023 +- [x] T133 [US2] Implement write-time validation (`ValidateDetailed`, REST, MCP `upstream_servers`, CLI) and load-time sanitize (`internal/config/oauth_validation.go`, write paths) — FR-023 +- [x] T134 [P] [US2] Failing test: `OAuthTransportWrapper` rewrites AS metadata fields from overrides, output passes mcp-go URL validation; synthesizes a document when metadata is unreachable and authz+token overrides exist; leaves non-metadata responses untouched (`internal/oauth/transport_wrapper_test.go`) — FR-024 +- [x] T135 [US2] Implement metadata rewrite/synthesis in the wrapper; pass `auth_server_metadata_url` to `OAuthConfig.AuthServerMetadataURL` (`internal/oauth/transport_wrapper.go`, `internal/oauth/config.go`) — FR-024 - [ ] T136 [P] [US2] Failing test: `extra_params` injected on a token endpoint `/oauth2/v1/exchange` learned from metadata; not on `/api/tokens/list`; heuristic still used when no endpoint known; 201→200 normalization follows the same match (`transport_wrapper_test.go`) — FR-025 -- [ ] T137 [US2] Implement endpoint-URL matching (`internal/oauth/transport_wrapper.go`) — FR-025 +- [x] T137 [US2] Implement endpoint-URL matching (`internal/oauth/transport_wrapper.go`) — FR-025 - [ ] T138 [P] [US2] Failing test: end-to-end with `httptest` AS on a non-standard metadata path + override; mcp-go authorization URL host equals override; token exchange and refresh hit the override (`internal/upstream/core/oauth_overrides_test.go`) — FR-024, FR-031 -- [ ] T139 [P] [US2] Failing test: discovery cache — 5 `createOAuthConfigInternal` calls → 1 request per discovery URL; different overrides → separate entries; failure cached 30 s then retried; LRU bound; invalidation on a differing `resource_metadata` (`internal/oauth/discovery_cache_test.go`) — FR-026, FR-027, SC-003 -- [ ] T140 [US2] Implement `discovery_cache.go` and route preflight discovery through it; invalidation hook from the 401 PRM-URL handling (`internal/oauth/discovery.go`, `discovery_cache.go`, `config.go`, `internal/upstream/core/connection.go` one call) — FR-026, FR-027 -- [ ] T141 [P] [US2] Failing test: scope waterfall — PRM scopes + AS advertises `offline_access` → appended once; explicit `oauth.scopes` → unchanged; AS-derived scopes → unchanged; empty → unchanged (`internal/oauth/config_test.go`) — FR-020 -- [ ] T142 [US2] Implement `offline_access` append (`internal/oauth/config.go`) — FR-020 -- [ ] T143 [P] [US2] Failing test: `grant_types_supported` without `refresh_token` → one Warn per server per process (zap observer); absent field → none (`internal/oauth/discovery_test.go`) — FR-021 -- [ ] T144 [US2] Implement the warning (`internal/oauth/discovery.go` or `config.go`) — FR-021 +- [x] T139 [P] [US2] Failing test: discovery cache — 5 `createOAuthConfigInternal` calls → 1 request per discovery URL; different overrides → separate entries; failure cached 30 s then retried; LRU bound; invalidation on a differing `resource_metadata` (`internal/oauth/discovery_cache_test.go`) — FR-026, FR-027, SC-003 +- [x] T140 [US2] Implement `discovery_cache.go` and route preflight discovery through it; invalidation hook from the 401 PRM-URL handling (`internal/oauth/discovery.go`, `discovery_cache.go`, `config.go`, `internal/upstream/core/connection.go` one call) — FR-026, FR-027 +- [x] T141 [P] [US2] Failing test: scope waterfall — PRM scopes + AS advertises `offline_access` → appended once; explicit `oauth.scopes` → unchanged; AS-derived scopes → unchanged; empty → unchanged (`internal/oauth/config_test.go`) — FR-020 +- [x] T142 [US2] Implement `offline_access` append (`internal/oauth/config.go`) — FR-020 +- [x] T143 [P] [US2] Failing test: `grant_types_supported` without `refresh_token` → one Warn per server per process (zap observer); absent field → none (`internal/oauth/discovery_test.go`) — FR-021 +- [x] T144 [US2] Implement the warning (`internal/oauth/discovery.go` or `config.go`) — FR-021 - [ ] T145 [US2] `ServerFieldMaskDecisions` rows `NotSecret` for the four fields; contracts OAuth projection; `cmd/generate-types` + regenerate `frontend/src/types/contracts.ts`; `make swagger`, commit `oas/` — FR-028 -- [ ] T150 [P] [US2] Failing test: OAuth client refuses https→http redirect to a non-loopback host and cross-origin redirect of a token/registration POST; same-origin redirect still works; with endpoint overrides and unreachable standard metadata mcp-go never hits `/authorize`, `/token`, `/register` defaults; override with a query string rejected at write time (`internal/oauth/transport_wrapper_test.go`, `internal/config/oauth_validation_test.go`) — FR-023, FR-024, FR-027a +- [x] T150 [P] [US2] Failing test: OAuth client refuses https→http redirect to a non-loopback host and cross-origin redirect of a token/registration POST; same-origin redirect still works; with endpoint overrides and unreachable standard metadata mcp-go never hits `/authorize`, `/token`, `/register` defaults; override with a query string rejected at write time (`internal/oauth/transport_wrapper_test.go`, `internal/config/oauth_validation_test.go`) — FR-023, FR-024, FR-027a - [ ] T146 [US2] `logSafeURL` everywhere a new URL is logged; test asserts no query string in logs (`internal/oauth`) — FR-030 -- [ ] T147 Docs: `docs/configuration.md` OAuth section (four fields, validation, precedence over discovery, `offline_access` rule, cache TTLs) +- [x] T147 Docs: `docs/configuration.md` OAuth section (four fields, validation, precedence over discovery, `offline_access` rule, cache TTLs) - [ ] T148 Gates (as T117) incl. server-tag build - [ ] T149 Cross-model review (opencode harness, gpt-6.1-sol), ≤10 rounds - T151–T159 reserved for 113-b follow-ups ## Slice 113-c — call-error-taxonomy (US3, G6) — T160–T189 -- [ ] T160 [P] [US3] Failing test: `callerr.Classify` table covering every FR-041 rule incl. `isError`, `ErrSessionTerminated`, `OAuthAuthorizationRequiredError`, recorded 401/403, `limiter.LimitError`, `managed.ErrConnectionGenerationChanged`, profile refusal, `jsonschema.ValidationError`, caller `context.Canceled`, `DeadlineExceeded` dispatched vs not, `*net.OpError`, mcp-go `*transport.Error`, recorded 502 with untyped mcp-go error, mcp-go `ErrInvalidParams`/`ErrInternalError`, `errors.New("custom -32001 message")` after a recorded 200, unknown (`internal/callerr/classify_test.go`) — FR-040, FR-041, FR-049 +- [x] T160 [P] [US3] Failing test: `callerr.Classify` table covering every FR-041 rule incl. `isError`, `ErrSessionTerminated`, `OAuthAuthorizationRequiredError`, recorded 401/403, `limiter.LimitError`, `managed.ErrConnectionGenerationChanged`, profile refusal, `jsonschema.ValidationError`, caller `context.Canceled`, `DeadlineExceeded` dispatched vs not, `*net.OpError`, mcp-go `*transport.Error`, recorded 502 with untyped mcp-go error, mcp-go `ErrInvalidParams`/`ErrInternalError`, `errors.New("custom -32001 message")` after a recorded 200, unknown (`internal/callerr/classify_test.go`) — FR-040, FR-041, FR-049 - [ ] T161 [US3] Implement `internal/callerr` — FR-040, FR-041 -- [ ] T162 [P] [US3] Failing test: `Outcome.AuditClass()` total mapping table (`internal/callerr/audit_test.go`) — FR-047 -- [ ] T163 [US3] Implement mapping; `audit_funnel.go` uses it so audit and activity agree (`internal/callerr`, `internal/server/audit_funnel.go`) — FR-047 -- [ ] T164 [P] [US3] Failing test: transport call recorder — status recorded for the request carrying the recorder ctx only; installed in every `CreateHTTPClient` branch (plain, static headers, trace, Retry-After, OAuth); concurrent calls do not cross-contaminate (`internal/transport/call_recorder_test.go`) — FR-042 +- [x] T162 [P] [US3] Failing test: `Outcome.AuditClass()` total mapping table (`internal/callerr/audit_test.go`) — FR-047 +- [x] T163 [US3] Implement mapping; `audit_funnel.go` uses it so audit and activity agree (`internal/callerr`, `internal/server/audit_funnel.go`) — FR-047 +- [x] T164 [P] [US3] Failing test: transport call recorder — status recorded for the request carrying the recorder ctx only; installed in every `CreateHTTPClient` branch (plain, static headers, trace, Retry-After, OAuth); concurrent calls do not cross-contaminate (`internal/transport/call_recorder_test.go`) — FR-042 - [ ] T165 [US3] Implement `WithCallRecorder` + round-tripper; install in `CreateHTTPClient` (`internal/transport/`) — FR-042 -- [ ] T166 [P] [US3] Failing test: `ActivityRecord` new fields omitempty; a pre-Spec-113 JSON fixture decodes byte-identically on re-encode (`internal/storage/activity_models_test.go`) — FR-043 -- [ ] T167 [US3] Add fields (`internal/storage/activity_models.go`) — FR-043 -- [ ] T168 [US3] Stamp fields at every tool-call activity write path (direct, `call_tool_*`, `code_execution` sub-calls, REST `/api/v1/tools/call`); recorder ctx installed at those dispatch sites (`internal/server/mcp.go`, `mcp_routing.go`, `mcp_code_execution.go`, `server.go`) — FR-044, FR-048 -- [ ] T169 [P] [US3] Failing integration test (SC-004): `httptest` Streamable HTTP upstream producing isError, 502 HTML, JSON-RPC -32001, reset, timeout, 404 session, 401; assert persisted record and `GET /api/v1/activity` JSON per class (`internal/server/call_error_taxonomy_test.go`) — SC-004 +- [x] T166 [P] [US3] Failing test: `ActivityRecord` new fields omitempty; a pre-Spec-113 JSON fixture decodes byte-identically on re-encode (`internal/storage/activity_models_test.go`) — FR-043 +- [x] T167 [US3] Add fields (`internal/storage/activity_models.go`) — FR-043 +- [x] T168 [US3] Stamp fields at every tool-call activity write path (direct, `call_tool_*`, `code_execution` sub-calls, REST `/api/v1/tools/call`); recorder ctx installed at those dispatch sites (`internal/server/mcp.go`, `mcp_routing.go`, `mcp_code_execution.go`, `server.go`) — FR-044, FR-048 +- [x] T169 [P] [US3] Failing integration test (SC-004): `httptest` Streamable HTTP upstream producing isError, 502 HTML, JSON-RPC -32001, reset, timeout, 404 session, 401; assert persisted record and `GET /api/v1/activity` JSON per class (`internal/server/call_error_taxonomy_test.go`) — SC-004 - [ ] T170 [US3] REST + SSE + contracts + `cmd/generate-types`; `ActivityFilter` `error_class`/`fault_domain`; `make swagger`, commit `oas/` (`internal/contracts/activity.go`, `internal/httpapi/activity.go`, `internal/runtime/activity_service.go`, `event_bus.go`) — FR-045, FR-046 - [ ] T171 [US3] CLI: `activity list|show -o json|yaml` fields; `--error-class`, `--fault-domain`; `activity show` table line (`cmd/mcpproxy/activity_cmd.go` + tests) — FR-045, FR-046 - [ ] T172 Docs: `docs/features/activity-log.md` + `docs/cli/activity-commands.md` (class table, fault domains, filters) From fd6790671797cff24b87388e72ce13ed313ff0a4 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 12 Oct 2026 05:33:45 +0000 Subject: [PATCH 02/11] chore(roadmap): regenerate ROADMAP.md after gardener checkbox sync --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index b13819da2..71f97a851 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1040,5 +1040,5 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [110-catalog-popularity](./specs/110-catalog-popularity/) | `in-flight` | 19/23 (83%) | | [111-personal-docker-image](./specs/111-personal-docker-image/) | — | — | | [112-client-header-forwarding](./specs/112-client-header-forwarding/) | `shipped` | 38/40 (95%) | -| [113-upstream-resilience](./specs/113-upstream-resilience/) | `drafted` | 0/100 (0%) | +| [113-upstream-resilience](./specs/113-upstream-resilience/) | `in-flight` | 40/100 (40%) | | [115-mcp-credential-lifecycle](./specs/115-mcp-credential-lifecycle/) | `shipped` | 86/87 (99%) | From 5d56924982ac4346c273829c4bc5ad1ffa9d7d5c Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 19 Oct 2026 05:31:02 +0000 Subject: [PATCH 03/11] chore(specs): gardener checkbox sync --- specs/113-upstream-resilience/tasks.md | 40 ++++++++++---------- specs/116-config-commit-consistency/tasks.md | 16 ++++---- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/specs/113-upstream-resilience/tasks.md b/specs/113-upstream-resilience/tasks.md index ab269a07c..fde4a6a92 100644 --- a/specs/113-upstream-resilience/tasks.md +++ b/specs/113-upstream-resilience/tasks.md @@ -70,24 +70,24 @@ Format: `[ID] [P?] [Story] Description (files) — FR`. `[P]` = can run in paral - [x] T167 [US3] Add fields (`internal/storage/activity_models.go`) — FR-043 - [x] T168 [US3] Stamp fields at every tool-call activity write path (direct, `call_tool_*`, `code_execution` sub-calls, REST `/api/v1/tools/call`); recorder ctx installed at those dispatch sites (`internal/server/mcp.go`, `mcp_routing.go`, `mcp_code_execution.go`, `server.go`) — FR-044, FR-048 - [x] T169 [P] [US3] Failing integration test (SC-004): `httptest` Streamable HTTP upstream producing isError, 502 HTML, JSON-RPC -32001, reset, timeout, 404 session, 401; assert persisted record and `GET /api/v1/activity` JSON per class (`internal/server/call_error_taxonomy_test.go`) — SC-004 -- [ ] T170 [US3] REST + SSE + contracts + `cmd/generate-types`; `ActivityFilter` `error_class`/`fault_domain`; `make swagger`, commit `oas/` (`internal/contracts/activity.go`, `internal/httpapi/activity.go`, `internal/runtime/activity_service.go`, `event_bus.go`) — FR-045, FR-046 -- [ ] T171 [US3] CLI: `activity list|show -o json|yaml` fields; `--error-class`, `--fault-domain`; `activity show` table line (`cmd/mcpproxy/activity_cmd.go` + tests) — FR-045, FR-046 -- [ ] T172 Docs: `docs/features/activity-log.md` + `docs/cli/activity-commands.md` (class table, fault domains, filters) +- [x] T170 [US3] REST + SSE + contracts + `cmd/generate-types`; `ActivityFilter` `error_class`/`fault_domain`; `make swagger`, commit `oas/` (`internal/contracts/activity.go`, `internal/httpapi/activity.go`, `internal/runtime/activity_service.go`, `event_bus.go`) — FR-045, FR-046 +- [x] T171 [US3] CLI: `activity list|show -o json|yaml` fields; `--error-class`, `--fault-domain`; `activity show` table line (`cmd/mcpproxy/activity_cmd.go` + tests) — FR-045, FR-046 +- [x] T172 Docs: `docs/features/activity-log.md` + `docs/cli/activity-commands.md` (class table, fault domains, filters) - [ ] T173 Gates (as T117) - [ ] T174 Cross-model review (opencode harness, gpt-6.1-sol), ≤10 rounds - T175–T189 reserved for 113-c follow-ups ## Slice 113-d — health-call-failure-rate (US4, G7) — T190–T219 -- [ ] T190 [P] [US4] Failing test: `callstats.Window` with injected clock — bucket rotation, 5 min expiry, counted vs uncounted, dominant kind, concurrent `Record` under `-race` (`internal/upstream/callstats/window_test.go`) — FR-060, FR-066 +- [x] T190 [P] [US4] Failing test: `callstats.Window` with injected clock — bucket rotation, 5 min expiry, counted vs uncounted, dominant kind, concurrent `Record` under `-race` (`internal/upstream/callstats/window_test.go`) — FR-060, FR-066 - [ ] T191 [US4] Implement `Window`, `Registry` (drop on remove/rename) (`internal/upstream/callstats/`) — FR-060, FR-066 -- [ ] T192 [P] [US4] Failing test: local predicate table (or 113-c classifier if merged) — isError, policy refusal, limiter, generation refusal, validation, cancel, auth → uncounted; network, post-dispatch timeout, 5xx, JSON-RPC error → failure; success → counted ok (`internal/upstream/callstats/classify_test.go`) — FR-061 -- [ ] T193 [US4] Implement predicate (`internal/upstream/callstats/classify.go`) — FR-061 -- [ ] T194 [P] [US4] Failing test: both choke points record — `Manager.CallTool`/`CallToolOnEpoch` and `code_execution` dispatch (`internal/upstream/manager_callstats_test.go`, `internal/server/mcp_code_execution_callstats_test.go`) — FR-062 -- [ ] T195 [US4] Record in `Manager.callTool` and after `CallToolOnEpoch` in `mcp_code_execution.go`; expose `Manager.CallStats(server)` and `RecordCallOutcome` (`internal/upstream/manager.go`, `internal/server/mcp_code_execution.go`) — FR-062 -- [ ] T196 [P] [US4] Failing test: calculator precedence and boundaries table (quarantined, disabled, disconnected, error, OAuth expired, refresh failed, missing secret, retry stopped each win; 4/4 → healthy; 5 @ 50% → healthy; 5 @ 60% → degraded; summary text) (`internal/health/calculator_test.go`) — FR-063, FR-064, FR-067 -- [ ] T197 [US4] Add `CallsInWindow`, `CallFailuresInWindow` and the degraded branch with constants (`internal/health/calculator.go`) — FR-063, FR-064, FR-065 -- [ ] T198 [US4] Fill the inputs at all three construction sites from `Manager.CallStats` (`internal/runtime/runtime.go`, `internal/server/server.go`, `internal/server/mcp.go`) + a test that the three agree — FR-063 +- [x] T192 [P] [US4] Failing test: local predicate table (or 113-c classifier if merged) — isError, policy refusal, limiter, generation refusal, validation, cancel, auth → uncounted; network, post-dispatch timeout, 5xx, JSON-RPC error → failure; success → counted ok (`internal/upstream/callstats/classify_test.go`) — FR-061 +- [x] T193 [US4] Implement predicate (`internal/upstream/callstats/classify.go`) — FR-061 +- [x] T194 [P] [US4] Failing test: both choke points record — `Manager.CallTool`/`CallToolOnEpoch` and `code_execution` dispatch (`internal/upstream/manager_callstats_test.go`, `internal/server/mcp_code_execution_callstats_test.go`) — FR-062 +- [x] T195 [US4] Record in `Manager.callTool` and after `CallToolOnEpoch` in `mcp_code_execution.go`; expose `Manager.CallStats(server)` and `RecordCallOutcome` (`internal/upstream/manager.go`, `internal/server/mcp_code_execution.go`) — FR-062 +- [x] T196 [P] [US4] Failing test: calculator precedence and boundaries table (quarantined, disabled, disconnected, error, OAuth expired, refresh failed, missing secret, retry stopped each win; 4/4 → healthy; 5 @ 50% → healthy; 5 @ 60% → degraded; summary text) (`internal/health/calculator_test.go`) — FR-063, FR-064, FR-067 +- [x] T197 [US4] Add `CallsInWindow`, `CallFailuresInWindow` and the degraded branch with constants (`internal/health/calculator.go`) — FR-063, FR-064, FR-065 +- [x] T198 [US4] Fill the inputs at all three construction sites from `Manager.CallStats` (`internal/runtime/runtime.go`, `internal/server/server.go`, `internal/server/mcp.go`) + a test that the three agree — FR-063 - [ ] T199 [US4] Health-change SSE: verify the existing poll/diff emits on a failure-rate change; add debounce only if a push path is needed (record which in the PR) — FR-068 - [ ] T200 [P] [US4] Integration test (SC-005): `httptest` upstream failing 6/10 → `/api/v1/servers` health degraded; advance clock past window → healthy — SC-005 - [ ] T201 Docs: health status page (`docs/` health section) — new degraded reason, thresholds @@ -97,14 +97,14 @@ Format: `[ID] [P?] [Story] Description (files) — FR`. `[P]` = can run in paral ## Slice 113-e — session-terminated-reinit (US5, G8) — T220–T239 -- [ ] T220 [P] [US5] Failing test pinning mcp-go v1.0.0 behaviour: 404 on a non-initialize POST → `ErrSessionTerminated` and session id cleared; 404 with no session id → also `ErrSessionTerminated`; a second `Initialize` on the same client/transport stores the new session id (or document that it cannot) (`internal/upstream/core/session_reinit_mcpgo_test.go`) — FR-088 -- [ ] T221 [US5] Implement `core.Client.SessionSnapshot()` and `ReinitializeSession(ctx)` without touching `connectionEpoch` (`internal/upstream/core/session_reinit.go`) — FR-080, FR-081, FR-083 -- [ ] T222 [P] [US5] Failing test (SC-006): `httptest` Streamable HTTP server that forgets the session once; single call → 1 initialize, call succeeds, state stays Ready, counter = 1 (`internal/upstream/managed/session_reinit_test.go`) — FR-080, FR-084, FR-085 +- [x] T220 [P] [US5] Failing test pinning mcp-go v1.0.0 behaviour: 404 on a non-initialize POST → `ErrSessionTerminated` and session id cleared; 404 with no session id → also `ErrSessionTerminated`; a second `Initialize` on the same client/transport stores the new session id (or document that it cannot) (`internal/upstream/core/session_reinit_mcpgo_test.go`) — FR-088 +- [x] T221 [US5] Implement `core.Client.SessionSnapshot()` and `ReinitializeSession(ctx)` without touching `connectionEpoch` (`internal/upstream/core/session_reinit.go`) — FR-080, FR-081, FR-083 +- [x] T222 [P] [US5] Failing test (SC-006): `httptest` Streamable HTTP server that forgets the session once; single call → 1 initialize, call succeeds, state stays Ready, counter = 1 (`internal/upstream/managed/session_reinit_test.go`) — FR-080, FR-084, FR-085 - [ ] T223 [P] [US5] Failing test: 10 concurrent calls on the same terminated session → exactly 1 initialize, 10 retries, all succeed; callers seeing a newer session id retry without re-init (`session_reinit_test.go`) — FR-082 -- [ ] T231 [P] [US5] Failing test: write/destructive tool after 404 → re-init, no repeat, `session_terminated` error, next call succeeds; changed tool hash after re-init → no retry, differential update runs; health `Ping` 404 first → following call joins the re-init (no request sent without a session id); cached-tool-count `ListTools` 404 → re-init, no `Error` state (`internal/upstream/managed/session_reinit_test.go`) — FR-080–FR-083 -- [ ] T232 [P] [US5] Failing test: a pinned call waiting on the re-init gate is refused with `ErrConnectionGenerationChanged` when the re-list shows its tool changed; after a re-init the upstream's `notifications/tools/list_changed` on the GET stream is still received (or, if the listener cannot be restarted, the full reconnect path runs and no retry happens) (`internal/upstream/managed/session_reinit_test.go`) — FR-083a +- [x] T231 [P] [US5] Failing test: write/destructive tool after 404 → re-init, no repeat, `session_terminated` error, next call succeeds; changed tool hash after re-init → no retry, differential update runs; health `Ping` 404 first → following call joins the re-init (no request sent without a session id); cached-tool-count `ListTools` 404 → re-init, no `Error` state (`internal/upstream/managed/session_reinit_test.go`) — FR-080–FR-083 +- [x] T232 [P] [US5] Failing test: a pinned call waiting on the re-init gate is refused with `ErrConnectionGenerationChanged` when the re-list shows its tool changed; after a re-init the upstream's `notifications/tools/list_changed` on the GET stream is still received (or, if the listener cannot be restarted, the full reconnect path runs and no retry happens) (`internal/upstream/managed/session_reinit_test.go`) — FR-083a - [ ] T224 [P] [US5] Failing test: retry also 404 → call fails and existing error path runs; re-initialize fails → original path; modern protocol or empty pre-call session id → no retry; non-404 errors → no retry (`session_reinit_test.go`) — FR-080, FR-084, FR-086 -- [ ] T225 [US5] Implement single-flight re-init + retry-once in `managed.Client` call, `ListTools` leader and prompt paths; only the final error reaches `isConnectionError`; schedule async tool refresh after re-init (`internal/upstream/managed/client.go`, `prompts.go`) — FR-080–FR-084 +- [x] T225 [US5] Implement single-flight re-init + retry-once in `managed.Client` call, `ListTools` leader and prompt paths; only the final error reaches `isConnectionError`; schedule async tool refresh after re-init (`internal/upstream/managed/client.go`, `prompts.go`) — FR-080–FR-084 - [ ] T226 [US5] Info log + per-client counter in diagnostics JSON (Prometheus counter if a seam exists) — FR-085 - [ ] T227 [P] [US5] Test: `CallToolOnEpoch` pinned call succeeds after re-init (epoch unchanged) — FR-083 - [ ] T228 Docs: troubleshooting note on session loss behaviour @@ -114,10 +114,10 @@ Format: `[ID] [P?] [Story] Description (files) — FR`. `[P]` = can run in paral ## Slice 113-f — mcp-cache-hints (US6, G9) — T240–T249 -- [ ] T240 [P] [US6] Failing test: modern (2026-07-28) `tools/list` and `prompts/list` on `/mcp`, `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/` carry `ttlMs:0`, `cacheScope:"private"`; legacy responses carry neither (`internal/server/cache_hints_test.go`) — FR-090, FR-092, SC-007 -- [ ] T241 [US6] Add `mcpserver.WithCacheHints(0, mcp.CacheScopePrivate)` to the four `NewMCPServer` calls (`internal/server/mcp.go`, `mcp_routing.go`) — FR-090, FR-091 +- [x] T240 [P] [US6] Failing test: modern (2026-07-28) `tools/list` and `prompts/list` on `/mcp`, `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/` carry `ttlMs:0`, `cacheScope:"private"`; legacy responses carry neither (`internal/server/cache_hints_test.go`) — FR-090, FR-092, SC-007 +- [x] T241 [US6] Add `mcpserver.WithCacheHints(0, mcp.CacheScopePrivate)` to the four `NewMCPServer` calls (`internal/server/mcp.go`, `mcp_routing.go`) — FR-090, FR-091 - [ ] T242 [US6] Re-run the three frozen tool-surface golden tests; confirm unchanged — FR-094 -- [ ] T243 [US6] Tick T063/T064 in `specs/058-mcp-2026-upgrade/tasks.md` — FR-093 +- [x] T243 [US6] Tick T063/T064 in `specs/058-mcp-2026-upgrade/tasks.md` — FR-093 - [ ] T244 Gates (as T117) - [ ] T245 Cross-model review (opencode harness, gpt-6.1-sol), ≤10 rounds - T246–T249 reserved diff --git a/specs/116-config-commit-consistency/tasks.md b/specs/116-config-commit-consistency/tasks.md index bb5e4c86f..d8229165a 100644 --- a/specs/116-config-commit-consistency/tasks.md +++ b/specs/116-config-commit-consistency/tasks.md @@ -25,7 +25,7 @@ Branch `116-pr1-config-commit` from `main`. ### Setup - [ ] T001 [US1] Add test seams (nil in production): `commitHooks`, `reconcileEntry` (at the `LoadConfiguredServers` entry on `main`), `beforeCommit`, `beforeApprovalLock`, `discoveryBeforeIndex`, `restPatchAfterParse`, `createAfterConfigRead` (`config_cow.go:93`) -- [ ] T002 [P] [US1] Add `scripts/check-upstream-write-sites.sh` (allowlist: `internal/storage/**`, `internal/runtime/commit*.go`, `*_test.go`) and wire it into `.github/workflows/unit-tests.yml`. It is expected to FAIL until T030 +- [x] T002 [P] [US1] Add `scripts/check-upstream-write-sites.sh` (allowlist: `internal/storage/**`, `internal/runtime/commit*.go`, `*_test.go`) and wire it into `.github/workflows/unit-tests.yml`. It is expected to FAIL until T030 ### Tests first (must fail on `main`) @@ -36,8 +36,8 @@ Branch `116-pr1-config-commit` from `main`. - [ ] T014 [P] [US1] `internal/server/create_commit_race_test.go`: T1.5 (parked add vs ApplyConfig profiles edit) - [ ] T015 [P] [US1] `internal/server/mcp_quarantine_index_test.go`: T1.6 (B1: MCP `quarantine_server` purges the index before returning) - [ ] T016 [P] [US1] `internal/server/shared_authbroker_patch_test.go`: T1.7 (REST and MCP patch keep `Shared` and `AuthBroker`) -- [ ] T017 [P] [US1] `internal/runtime/configsvc/generations_test.go`: generation rule table (data-model §2), incarnation kept on update and reset on recreate, `SeedVersion` monotonic (T1.9) -- [ ] T018 [P] [US1] `internal/storage/server_commit_test.go`: `ApplyServerCommit` is all-or-nothing (inject an error on the 2nd row → no row changed), writes the meta generation, stamps Generation/Incarnation +- [x] T017 [P] [US1] `internal/runtime/configsvc/generations_test.go`: generation rule table (data-model §2), incarnation kept on update and reset on recreate, `SeedVersion` monotonic (T1.9) +- [x] T018 [P] [US1] `internal/storage/server_commit_test.go`: `ApplyServerCommit` is all-or-nothing (inject an error on the 2nd row → no row changed), writes the meta generation, stamps Generation/Incarnation - [ ] T018a [P] [US1] `internal/runtime/commit_bootstrap_test.go`: T1.10 (boot with an empty storage and manager repairs the projection and schedules every enabled server; an unchanged `SaveConfiguration` still writes the file; restart keeps generations of unchanged rows) - [ ] T018b [P] [US1] `internal/runtime/commit_removal_exclusion_test.go`: T1.11 (formerly T2.3; regression coverage that a parked removal blocks a B toggle, REST update and MCP patch, which then get 404) - [ ] T018c [P] [US1] `internal/runtime/discovery_purge_race_test.go`: T1.12 (a pass parked after its approval check vs `QuarantineServer(true)` → no re-index) @@ -52,11 +52,11 @@ Branch `116-pr1-config-commit` from `main`. ### Implementation -- [ ] T020 [US1] `internal/config/server_entry_equal.go`: `ServerEntryEqual` (ignores Created/Updated; includes the explicit bit, Shared, AuthBroker) with a table test +- [x] T020 [US1] `internal/config/server_entry_equal.go`: `ServerEntryEqual` (ignores Created/Updated; includes the explicit bit, Shared, AuthBroker) with a table test - [ ] T020a [US1] `internal/commitview` leaf package: `ServerGen{Gen, Incarnation}` (PR2 adds `OAuthEpoch`, `CredentialBinding`, `Binding()`), `ErrStaleGeneration`; `TestCommitviewIsLeaf` (`go list -deps`, no module-internal import). `configsvc.ServerGen` and `upstream.ErrStaleGeneration` are aliases (review R7.2) - [ ] T021 [US1] `configsvc`: remove `SetPrePublishHook` (admission moves to commit step 2, R1.7); `ServerGen` (alias of `commitview.ServerGen`), `Snapshot.ServerGenerations`, `Prepare(PrepareInput{Config, Source, Replaced})`/`Publish`/`SeedVersion`; the replaced-name row of the generation table checked first, and `Changes` computed in `Prepare` (review R8.2). Re-express `Update`/`UpdateIfCurrent` on top. Remove `ReloadFromFile`'s raw publish (makes T017 pass) - [ ] T022 [US1] storage: `UpstreamRecord.Generation/Incarnation`, `ApplyServerCommit` (one tx; `Saves []ServerSave{Config, Stamp}` written with each row's prepared stamp verbatim, zero or above-`G` stamps rejected, review R9.3; saves through the quarantine-keeping invariant; deletes as today: row + call history; `Replaces` deleted before `Saves`, any other delete/save overlap an invariant error, review R8.2), meta key (makes T018 pass) -- [ ] T023 [US1] `internal/runtime/commit.go`: `Commit`, `CommitTx` ops (with the `replaced` bookkeeping and the `Replaced` change kind, makes T018f pass; review R8.2), pipeline steps 1-6 and 8 plus after-unlock (plan §Commit pipeline). Approval locks taken in sorted order in step 4 for every name step 6 writes (changed names, hook names, removes, replacements, OAuth clears and projection-repair saves; every configured server on a global approval-policy change; plan.md step 4, PR1 review rounds 4-5), with `UnderApprovalLock` hooks. Compensating disk restore on a storage failure: capture the raw file state `{exists, bytes, mode}` inside L0 before step 5 and restore **that** (same bytes and mode, or remove the file when it was absent), never a config rebuilt from memory, with the self-write marker bookkeeping (forget the failed write's marker, record one for the restored bytes) and `desiredCfg` untouched (makes T018e and T018g pass; reviews R5.5, R9.2). The batch's per-save stamps are copied from `PreparedSnapshot.ServerGenerations` and asserted equal before `ApplyServerCommit` (makes T018i pass; review R9.3). Re-entry guard +- [x] T023 [US1] `internal/runtime/commit.go`: `Commit`, `CommitTx` ops (with the `replaced` bookkeeping and the `Replaced` change kind, makes T018f pass; review R8.2), pipeline steps 1-6 and 8 plus after-unlock (plan §Commit pipeline). Approval locks taken in sorted order in step 4 for every name step 6 writes (changed names, hook names, removes, replacements, OAuth clears and projection-repair saves; every configured server on a global approval-policy change; plan.md step 4, PR1 review rounds 4-5), with `UnderApprovalLock` hooks. Compensating disk restore on a storage failure: capture the raw file state `{exists, bytes, mode}` inside L0 before step 5 and restore **that** (same bytes and mode, or remove the file when it was absent), never a config rebuilt from memory, with the self-write marker bookkeeping (forget the failed write's marker, record one for the restored bytes) and `desiredCfg` untouched (makes T018e and T018g pass; reviews R5.5, R9.2). The batch's per-save stamps are copied from `PreparedSnapshot.ServerGenerations` and asserted equal before `ApplyServerCommit` (makes T018i pass; review R9.3). Re-entry guard - [ ] T024 [US1] `internal/runtime/commit_reconcile.go`: move `LoadConfiguredServers`' storage phase into step 6 (diff against the stored view; OAuth-config-change clear; newly-quarantined index purge, FR-008; orphan GC on the working copy, with the empty guard at boot only). Replace the boot call (`lifecycle.go:206`) with `Commit("boot", ReconcileLive + Bootstrap)`; `Bootstrap()` anywhere else is an invariant error, and every other reconcile is `ReconcileLive()` alone (makes T018j pass; review R9.6). `LoadConfiguredServers` is deleted once T026/T027 have converted its other callers. Delete the removal goroutines (removal is synchronous in step 6) - [ ] T024a [US1] D15: move a discovery pass's final eligibility/generation check and all its index, StateView and last-good writes into one hold of L1 (coordinate with Spec 117 PR-3 G8; skip if already landed) (makes T018c pass). `ReconcileLive()`; delete `LoadConfiguredServers(cfg)`'s captured-argument form (D14) - [ ] T024b [US1] `checkToolApprovalsHeld` / `deleteToolApprovalHeld` caller-held variants and the inventory of helpers inside the D15 hold; `resolveToolQuarantineGateHeld` reads the row + `meta.quarantine_enabled` (written by the commit tx) (D16) (makes T018d pass) @@ -65,12 +65,12 @@ Branch `116-pr1-config-commit` from `main`. - [ ] T026 [US1] `ApplyConfig`/`applyConfigLocked`, `ReloadConfiguration`, `UpdateConfig`, `UpdateListenAddress`, `SaveConfiguration` (persist the live config, no storage read), `gateInitialConfig`, `SetServerShared` → `Commit` (makes T011 pass) - [ ] T027 [US1] `EnableServer`, `BulkEnableServers`, `QuarantineServer` (index purge in the commit; baseline approval after the commit, which keeps the `CommitResult` and passes its incarnation on rather than recapturing by name; PR2 T053 adds the check, review R9.5), `RestartServer`'s disk refresh → `Commit` (makes T013 pass) - [ ] T028 [US1] `internal/server`: `createServer` → `Commit(CreateServer)` and delete `createMu` (the mutex only: the #1570 create-only behaviour and test assertions stay, plan.md `createMu` note); `removeServerStorage` → `Commit(RemoveServer)` (PR1 deletes as today); `UpdateServer` → `Commit(UpdateServer)` with the in-place mutation removed; registry source add/edit/remove → `Commit(MutateGlobal)` (makes T014 and T016 pass) -- [ ] T029 [US1] `internal/server/mcp.go`: update/patch merge inside `UpdateServer`; the result's connection status comes from the generation's worker result (bounded wait, as today): the update returns the server's committed generation and the monitor skips any registered instance stamped below it, so the replaced instance's ready/error state is never reported (PR1 review round 6); quarantine → `Commit(SetQuarantined)`; remove → `Commit(RemoveServer)` (makes T015 and the MCP half of T012 pass) +- [x] T029 [US1] `internal/server/mcp.go`: update/patch merge inside `UpdateServer`; the result's connection status comes from the generation's worker result (bounded wait, as today): the update returns the server's committed generation and the monitor skips any registered instance stamped below it, so the replaced instance's ready/error state is never reported (PR1 review round 6); quarantine → `Commit(SetQuarantined)`; remove → `Commit(RemoveServer)` (makes T015 and the MCP half of T012 pass) - [ ] T029a [US1] If Spec 117 PR-2 has merged: convert `CommitServerApproval`/`FinishServerApproval` to `Commit(ExpectIncarnation(PR2: generation until then), SetQuarantined(false), UnderApprovalLock(...))` with its tests unchanged. Otherwise: add `UnderApprovalLock` with a unit test (hook runs under the lock; a hook error aborts with nothing written) -- [ ] T030 [US1] `internal/httpapi/server.go` PATCH: move omitted-field, map-merge, isolation and forward-header resolution into a `func(cur *config.ServerConfig) error` passed down to `UpdateServer` (makes T012 pass; T002 now passes) +- [x] T030 [US1] `internal/httpapi/server.go` PATCH: move omitted-field, map-merge, isolation and forward-header resolution into a `func(cur *config.ServerConfig) error` passed down to `UpdateServer` (makes T012 pass; T002 now passes) - [ ] T031 [US1] `TestCommit_*` + `TestLockOrder_*` at `-race -count=20` with `GOMAXPROCS=1` and `4`; the CI skip lane under `-tags server`; both lint passes; `./scripts/test-api-e2e.sh` - [ ] T032 [US1] Live L1 on the qa070 harness ([quickstart.md](quickstart.md)); evidence in `evidence/s116-pr1/EVIDENCE.md` -- [ ] T033 [US1] Docs: `docs/architecture.md` "Config commit" section (pipeline + lock order); CLAUDE.md Recent Changes line +- [x] T033 [US1] Docs: `docs/architecture.md` "Config commit" section (pipeline + lock order); CLAUDE.md Recent Changes line - [ ] T034 [US1] opencode Sol review in chunks (commit/storage; writers; httpapi/mcp). Fix in-scope findings only **Checkpoint**: every server writer goes through `Commit`, and storage no From 7b43ddec6c63ca90cf77727c8a27dd334784425d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 19 Oct 2026 05:31:05 +0000 Subject: [PATCH 04/11] chore(roadmap): regenerate ROADMAP.md after gardener checkbox sync --- ROADMAP.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 11aea3f5a..05583172c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1027,7 +1027,7 @@ graph LR | SDK v1 migration | Todo (parked) | P3 | — | | | | Upgrade awareness & guided update | Done | P0 | — | [079-upgrade-nudge](./specs/079-upgrade-nudge/) | | | Connect step trust: preview, visible backup, one-click undo | Done | P0 | — | [078-connect-trust-preview](./specs/078-connect-trust-preview/) | | -| Spec 116 config commit consistency: one commit section, atomic removal, upstream retirement | Done | P0 | 81/124 (65%) | [116-config-commit-consistency](./specs/116-config-commit-consistency/) | #1590 #1600 #1608 #1612 #1621 | +| Spec 116 config commit consistency: one commit section, atomic removal, upstream retirement | Done | P0 | 89/124 (72%) | [116-config-commit-consistency](./specs/116-config-commit-consistency/) | #1590 #1600 #1608 #1612 #1621 | | Spec 117 review-bound approvals: durable baselines, hash-bound approvals, ordered tool inventories | Done | P0 | 46/50 (92%) | [117-review-bound-approvals](./specs/117-review-bound-approvals/) | #1604 #1605 #1609 | | Non-Docker sandbox isolation (Landlock) `MCP-34` | Done | P1 | — | | | | Spec 076 deterministic offline tool-scanner `MCP-3574` | Done | P1 | 22/24 (92%) | [076-deterministic-tool-scanner](./specs/076-deterministic-tool-scanner/) | | @@ -1036,7 +1036,7 @@ graph LR | Scanner simplification (deterministic default, opt-in deep scan) | Done | P1 | 38/42 (90%) | [077-scanner-simplification](./specs/077-scanner-simplification/) | | | Deferred-schema serialization for the direct tools/list surface (spec 102) | Done | P1 | 89/89 (100%) | [102-schema-deferred](./specs/102-schema-deferred/) | #1063 | | Agent-token scope hardening: every MCP request authorized by its own scope (spec 105) | Done | P1 | 111/113 (98%) | [105-agent-scope-hardening](./specs/105-agent-scope-hardening/) | | -| Spec 113 upstream resilience: OAuth refresh, discovery, call-error taxonomy, session re-init | Done | P1 | 0/100 (0%) | [113-upstream-resilience](./specs/113-upstream-resilience/) | #1495 #1498 #1499 #1501 #1502 #1504 #1510 #1650 | +| Spec 113 upstream resilience: OAuth refresh, discovery, call-error taxonomy, session re-init | Done | P1 | 60/100 (60%) | [113-upstream-resilience](./specs/113-upstream-resilience/) | #1495 #1498 #1499 #1501 #1502 #1504 #1510 #1650 | | Spec 115 admin MCP credentials tool: client credentials + agent token lifecycle | Done | P1 | 86/87 (99%) | [115-mcp-credential-lifecycle](./specs/115-mcp-credential-lifecycle/) | #1557 | | Quarantine/approval testing pilot: independent policy model, scenario inventory, mutation gate | Done | P1 | — | | #1619 #1631 #1634 | | Tray↔core decoupling: socket/REST API only, no config-file reads | Done | P2 | — | | | @@ -1168,7 +1168,7 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [110-catalog-popularity](./specs/110-catalog-popularity/) | `in-flight` | 19/23 (83%) | | [111-personal-docker-image](./specs/111-personal-docker-image/) | — | — | | [112-client-header-forwarding](./specs/112-client-header-forwarding/) | `shipped` | 38/40 (95%) | -| [113-upstream-resilience](./specs/113-upstream-resilience/) | `in-flight` | 40/100 (40%) | +| [113-upstream-resilience](./specs/113-upstream-resilience/) | `in-flight` | 60/100 (60%) | | [115-mcp-credential-lifecycle](./specs/115-mcp-credential-lifecycle/) | `shipped` | 86/87 (99%) | -| [116-config-commit-consistency](./specs/116-config-commit-consistency/) | `in-flight` | 81/124 (65%) | +| [116-config-commit-consistency](./specs/116-config-commit-consistency/) | `in-flight` | 89/124 (72%) | | [117-review-bound-approvals](./specs/117-review-bound-approvals/) | `in-flight` | 46/50 (92%) | From ac22202319bd34464bd1faac2ebc11f41d576809 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 2 Nov 2026 05:23:13 +0000 Subject: [PATCH 05/11] chore(specs): gardener checkbox sync --- specs/058-mcp-2026-upgrade/tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specs/058-mcp-2026-upgrade/tasks.md b/specs/058-mcp-2026-upgrade/tasks.md index b98680c56..27200a864 100644 --- a/specs/058-mcp-2026-upgrade/tasks.md +++ b/specs/058-mcp-2026-upgrade/tasks.md @@ -155,7 +155,7 @@ Single Go project. Backend paths are repo-relative: `internal/`, `cmd/`, `bench/ - [x] T063 [P] [US5] Write failing tests that list/read responses carry `ttlMs` and an identity-appropriate `cacheScope`, in `internal/server/cache_hints_test.go` - [x] T064 [US5] Configure cache hints — private for identity-scoped surfaces, public for shared ones — in `internal/server/mcp_routing.go` and `internal/server/mcp.go` -- [ ] T065 [P] [US5] Write a failing test that repeated `tools/list` calls are byte-identical under unchanged state, in `internal/server/stateless_list_test.go` +- [x] T065 [P] [US5] Write a failing test that repeated `tools/list` calls are byte-identical under unchanged state, in `internal/server/stateless_list_test.go` - [ ] T066 [US5] Make tool ordering deterministic wherever map iteration currently leaks in, in `internal/server/mcp_routing.go` - [ ] T067 [P] [US5] Write a failing test that external `$ref`s are not dereferenced and that schemas validate as JSON Schema 2020-12, in `internal/server/mcp_input_validation_test.go` - [ ] T068 [US5] Install a rejecting loader so no external `$ref` is fetched, and confirm the dialect default, in `internal/server/mcp_input_validation.go` From f3a63ca7699cf82296ab3ccdd4ef9216201ce0ce Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 2 Nov 2026 05:23:21 +0000 Subject: [PATCH 06/11] chore(roadmap): regenerate ROADMAP.md after gardener checkbox sync --- ROADMAP.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 575c8e46b..3d91f4871 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1012,7 +1012,7 @@ graph LR | 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/) | | -| MCP protocol upgrade to 2026-07-28 revision | In progress | P1 | 40/81 (49%) | [058-mcp-2026-upgrade](./specs/058-mcp-2026-upgrade/) | | +| MCP protocol upgrade to 2026-07-28 revision | In progress | P1 | 41/81 (51%) | [058-mcp-2026-upgrade](./specs/058-mcp-2026-upgrade/) | | | Spec 108 profiles v3: scoped profiles, client binding, scope-aware observability | In progress | P1 | 194/195 (99%) | [108-profiles-v3](./specs/108-profiles-v3/) | | | Spec 109 navigation, scope filters and cross-surface UX consistency | In progress | P1 | 257/258 (100%) | [109-ux-navigation-consistency](./specs/109-ux-navigation-consistency/) | | | Planning/docs truth automation | In progress | P2 | — | | | @@ -1122,7 +1122,7 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [055-frontend-major-upgrades](./specs/055-frontend-major-upgrades/) | `shipped` | 23/24 (96%) | | [056-output-schema-validation](./specs/056-output-schema-validation/) | `in-flight` | 22/24 (92%) | | [057-in-proxy-profiles](./specs/057-in-proxy-profiles/) | `in-flight` | 20/25 (80%) | -| [058-mcp-2026-upgrade](./specs/058-mcp-2026-upgrade/) | `in-flight` | 40/81 (49%) | +| [058-mcp-2026-upgrade](./specs/058-mcp-2026-upgrade/) | `in-flight` | 41/81 (51%) | | [059-output-sanitisation](./specs/059-output-sanitisation/) | `shipped` | 24/25 (96%) | | [060-settings-page](./specs/060-settings-page/) | `shipped` | 16/16 (100%) | | [064-glass-cockpit](./specs/064-glass-cockpit/) | — | — | From 7865f544ff8a41a9195afed59a48610cb15f08d0 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 16 Nov 2026 06:23:00 +0000 Subject: [PATCH 07/11] chore(specs): gardener checkbox sync --- specs/123-oauth-token-encryption/tasks.md | 80 +++++++++++------------ 1 file changed, 40 insertions(+), 40 deletions(-) diff --git a/specs/123-oauth-token-encryption/tasks.md b/specs/123-oauth-token-encryption/tasks.md index 772ca6516..983d3ae23 100644 --- a/specs/123-oauth-token-encryption/tasks.md +++ b/specs/123-oauth-token-encryption/tasks.md @@ -14,9 +14,9 @@ ## Phase 0: docs correction with today's facts (FR-040, FR-041) -- [ ] T090 [P] [US5] `docs/features/oauth-authentication.md`: fix lines 83, 216-224, 402 per plan "Docs plan / PR-1" (tokens are readable JSON in `config.db`, protected by file permissions; remove the keyring table) -- [ ] T091 [P] [US5] `docs/docker-isolation.md:515`, `docs/features/docker-isolation.md:435`, `docs/features/sandbox-isolation.md:94,109`: state plainly that `config.db` holds the tokens in readable form; `specs/023-oauth-state-persistence/plan.md:31` annotation; the `bbolt.go` comment -- [ ] T092 [US5] Grep gate: `grep -rniE 'keyring' docs/features/oauth-authentication.md` returns no storage claim; probe the published URLs after merge +- [x] T090 [P] [US5] `docs/features/oauth-authentication.md`: fix lines 83, 216-224, 402 per plan "Docs plan / PR-1" (tokens are readable JSON in `config.db`, protected by file permissions; remove the keyring table) +- [x] T091 [P] [US5] `docs/docker-isolation.md:515`, `docs/features/docker-isolation.md:435`, `docs/features/sandbox-isolation.md:94,109`: state plainly that `config.db` holds the tokens in readable form; `specs/023-oauth-state-persistence/plan.md:31` annotation; the `bbolt.go` comment +- [x] T092 [US5] Grep gate: `grep -rniE 'keyring' docs/features/oauth-authentication.md` returns no storage claim; probe the published URLs after merge ## PR-2 @@ -24,33 +24,33 @@ ### Tests first -- [ ] T001 [P] [US1] `internal/tokenseal/tokenseal_test.go`: round trip; 1 000 seals of the same plaintext give 1 000 distinct nonces and ciphertexts; envelope matches `^enc:v1:[0-9a-f]{16}:[A-Za-z0-9+/=]+$`; `Classify` table (`{…}` → plaintext, `enc:v1:` → sealed + kid, `enc:v2:` → unsupported, empty / other → malformed); `Seal` rejects plaintext over 1 MiB and a bucket name or bucket key containing a NUL byte (`Open` likewise) +- [x] T001 [P] [US1] `internal/tokenseal/tokenseal_test.go`: round trip; 1 000 seals of the same plaintext give 1 000 distinct nonces and ciphertexts; envelope matches `^enc:v1:[0-9a-f]{16}:[A-Za-z0-9+/=]+$`; `Classify` table (`{…}` → plaintext, `enc:v1:` → sealed + kid, `enc:v2:` → unsupported, empty / other → malformed); `Seal` rejects plaintext over 1 MiB and a bucket name or bucket key containing a NUL byte (`Open` likewise) - [ ] T002 [P] [US2] `internal/tokenseal/open_errors_test.go`: `Open` with nil key → `no_key`; other key → `key_mismatch` with both kids; prefix kid edited to any value other than the configured kid → `key_mismatch` (no decrypt attempted); prefix kid edited to the configured kid, other bucket key, or other bucket name → `auth_failed`; damaged header or empty payload → `malformed` under every key state; precedence header → key state → payload, so characters outside the base64 alphabet or a `=` anywhere other than as the last one or two payload characters → `malformed` only with the matching key and `no_key` / `key_mismatch` under no key / another key; with the matching key, a payload of base64-alphabet characters with at most two trailing `=` that does not decode (wrong length for its padding) or is shorter than nonce + tag (truncation), and any GCM failure → `auth_failed`; explicit cases `AAAA=` → `auth_failed`, `AA=A` → `malformed`; `enc:v2:` → `unsupported_version` -- [ ] T003 [P] [US3] `internal/tokenseal/key_test.go`: `ParseKey` table (32 bytes std base64 with and without padding, surrounding whitespace and one trailing newline accepted; 31/33 bytes, URL alphabet with `-`/`_`, empty, non-base64 rejected with a fixed message containing no input); HKDF known-answer vectors for the record key and kid; `fmt.Sprintf("%v|%+v|%#v", k)` and `json.Marshal(k)` contain neither the raw key nor its base64 (`String`/`GoString` print the key id only) -- [ ] T004 [P] [US1] `internal/tokenseal/leaf_test.go`: `go list -deps` shows only standard-library packages (pattern of `TestCommitviewIsLeaf`) +- [x] T003 [P] [US3] `internal/tokenseal/key_test.go`: `ParseKey` table (32 bytes std base64 with and without padding, surrounding whitespace and one trailing newline accepted; 31/33 bytes, URL alphabet with `-`/`_`, empty, non-base64 rejected with a fixed message containing no input); HKDF known-answer vectors for the record key and kid; `fmt.Sprintf("%v|%+v|%#v", k)` and `json.Marshal(k)` contain neither the raw key nor its base64 (`String`/`GoString` print the key id only) +- [x] T004 [P] [US1] `internal/tokenseal/leaf_test.go`: `go list -deps` shows only standard-library packages (pattern of `TestCommitviewIsLeaf`) ### Implementation -- [ ] T005 [US1] `internal/tokenseal/tokenseal.go`: `Key`, `ParseKey`, `ID`, `Seal`, `Open`, `Classify`, `Shape`, `Reason`, `OpenError` per plan D1-D3, D5 (makes T001-T004 pass) +- [x] T005 [US1] `internal/tokenseal/tokenseal.go`: `Key`, `ParseKey`, `ID`, `Seal`, `Open`, `Classify`, `Shape`, `Reason`, `OpenError` per plan D1-D3, D5 (makes T001-T004 pass) ## Phase 2: storage codec seam and fail-closed writers (FR-010..016) ### Tests first -- [ ] T010 [P] [US1] `internal/storage/oauth_seal_test.go`: with `WithOAuthTokenKey(k)`, every write method (`SaveOAuthToken`, `UpdateOAuthTokenIfBound`, `SaveOAuthClientIfBound` all modes, `UpdateOAuthToken`, `UpdateOAuthClientCredentials`, `SaveOAuthClientCredentialsIf*`, `ClearOAuthClient*`) leaves an `enc:v1` value whose kid is `k.ID()`; every read method returns the same record it would for a plaintext row; revision increases per write as today; a write over a plaintext row sets `meta/oauth_seal_compact_advised` in the same transaction, a write over a sealed row does not -- [ ] T011 [P] [US1] `internal/storage/oauth_plaintext_golden_test.go`: without a key, the bytes written for a token save, a DCR save and a refresh-style update equal `json.Marshal` of the record (SC-003) -- [ ] T012 [P] [US2] `internal/storage/oauth_undecryptable_test.go`: one table over every mutator listed in FR-013 (including the unconditional ones with no production caller) against an undecryptable row (no key / other key / swapped envelope): returns `ErrOAuthTokenUndecryptable` with the right reason and the raw bytes are unchanged (exception, FR-013: with no key, `SaveOAuthToken` overwrites a corrupt non-`enc:` value as before the feature, while any `enc:` row is always refused, and with a key every undecodable row is refused); key-only deletes (`DeleteOAuthToken`, `ClearOAuthTokenForStandaloneLogout`, `ClearOAuthState`, the Spec 116 purge (`purgeServerTx`, driven through `purgetest`), commit `OAuthClears`) still remove the row; reads return the typed error, not "not found" -- [ ] T013 [P] [US2] `internal/storage/oauth_list_tolerant_test.go`: one undecryptable row and one plaintext row with invalid JSON among three good rows → `ListOAuthTokens` returns the three; `ListOAuthTokenRows` puts every row in exactly one class (`plaintext | sealed | undecryptable`) with `key_mismatch` as a reason only; `CleanupOrphanedOAuthTokens` deletes a decodable orphan, keeps both bad rows (also when their key prefix names no configured server) and reports them -- [ ] T014 [P] [US1] `internal/storage/oauth_sweep_test.go`: seed several hundred ~1 KiB plaintext rows (spanning many leaf pages) plus sealed and undecryptable rows; a plaintext row with invalid JSON and one over the 1 MiB `Seal` bound are skipped with a warning (observed logger: bucket key and reason `malformed` / `too_large`, never the value) and left unchanged while the other plaintext rows are sealed; `SealPlaintextOAuthTokens` leaves zero valid plaintext rows, touches no sealed or undecryptable row, and sets the marker only when it sealed ≥1 row; with `putOAuthRecordHook` failing on the second write the whole transaction rolls back (first row still plaintext); no-op without a key -- [ ] T015 [P] [US1] `internal/storage/oauth_codec_source_test.go`: `TestOAuthBucketValuesOnlyThroughCodec` per plan D6 (stdlib `go/parser` + `go/types`, receiver type `OAuthTokenRecord`; bucket access on `OAuthTokenBucket` only in the named exemptions; `UpstreamRecord`/`OAuthCompletionEvent` calls in `oauth_binding.go` not flagged) and `TestStorageOpenSitesPassOAuthKey` (every non-test `storage.NewManager(`/`storage.NewBoltDB(` call in the module passes `WithOAuthTokenKey`; the delete-only standalone `auth logout` open passes an explicit nil, named as the one exemption); both fail on `main` -- [ ] T016 [US1] `internal/storage/oauth_raw_file_test.go`: `TestOAuthTokensNotInRawFile` per plan test plan (markers for access token, refresh token, client secret; sweep → close → `bbolt.Compact` → markers absent from the compacted file; a login-style write with the key set never appears in the live file; control run without a key finds every marker) +- [x] T010 [P] [US1] `internal/storage/oauth_seal_test.go`: with `WithOAuthTokenKey(k)`, every write method (`SaveOAuthToken`, `UpdateOAuthTokenIfBound`, `SaveOAuthClientIfBound` all modes, `UpdateOAuthToken`, `UpdateOAuthClientCredentials`, `SaveOAuthClientCredentialsIf*`, `ClearOAuthClient*`) leaves an `enc:v1` value whose kid is `k.ID()`; every read method returns the same record it would for a plaintext row; revision increases per write as today; a write over a plaintext row sets `meta/oauth_seal_compact_advised` in the same transaction, a write over a sealed row does not +- [x] T011 [P] [US1] `internal/storage/oauth_plaintext_golden_test.go`: without a key, the bytes written for a token save, a DCR save and a refresh-style update equal `json.Marshal` of the record (SC-003) +- [x] T012 [P] [US2] `internal/storage/oauth_undecryptable_test.go`: one table over every mutator listed in FR-013 (including the unconditional ones with no production caller) against an undecryptable row (no key / other key / swapped envelope): returns `ErrOAuthTokenUndecryptable` with the right reason and the raw bytes are unchanged (exception, FR-013: with no key, `SaveOAuthToken` overwrites a corrupt non-`enc:` value as before the feature, while any `enc:` row is always refused, and with a key every undecodable row is refused); key-only deletes (`DeleteOAuthToken`, `ClearOAuthTokenForStandaloneLogout`, `ClearOAuthState`, the Spec 116 purge (`purgeServerTx`, driven through `purgetest`), commit `OAuthClears`) still remove the row; reads return the typed error, not "not found" +- [x] T013 [P] [US2] `internal/storage/oauth_list_tolerant_test.go`: one undecryptable row and one plaintext row with invalid JSON among three good rows → `ListOAuthTokens` returns the three; `ListOAuthTokenRows` puts every row in exactly one class (`plaintext | sealed | undecryptable`) with `key_mismatch` as a reason only; `CleanupOrphanedOAuthTokens` deletes a decodable orphan, keeps both bad rows (also when their key prefix names no configured server) and reports them +- [x] T014 [P] [US1] `internal/storage/oauth_sweep_test.go`: seed several hundred ~1 KiB plaintext rows (spanning many leaf pages) plus sealed and undecryptable rows; a plaintext row with invalid JSON and one over the 1 MiB `Seal` bound are skipped with a warning (observed logger: bucket key and reason `malformed` / `too_large`, never the value) and left unchanged while the other plaintext rows are sealed; `SealPlaintextOAuthTokens` leaves zero valid plaintext rows, touches no sealed or undecryptable row, and sets the marker only when it sealed ≥1 row; with `putOAuthRecordHook` failing on the second write the whole transaction rolls back (first row still plaintext); no-op without a key +- [x] T015 [P] [US1] `internal/storage/oauth_codec_source_test.go`: `TestOAuthBucketValuesOnlyThroughCodec` per plan D6 (stdlib `go/parser` + `go/types`, receiver type `OAuthTokenRecord`; bucket access on `OAuthTokenBucket` only in the named exemptions; `UpstreamRecord`/`OAuthCompletionEvent` calls in `oauth_binding.go` not flagged) and `TestStorageOpenSitesPassOAuthKey` (every non-test `storage.NewManager(`/`storage.NewBoltDB(` call in the module passes `WithOAuthTokenKey`; the delete-only standalone `auth logout` open passes an explicit nil, named as the one exemption); both fail on `main` +- [x] T016 [US1] `internal/storage/oauth_raw_file_test.go`: `TestOAuthTokensNotInRawFile` per plan test plan (markers for access token, refresh token, client secret; sweep → close → `bbolt.Compact` → markers absent from the compacted file; a login-style write with the key set never appears in the live file; control run without a key finds every marker) ### Implementation -- [ ] T020 [US1] `internal/storage/options.go`: `Option`, `WithOAuthTokenKey`; variadic `opts` on `NewBoltDB` and `NewManager`; `BoltDB.oauthKey` -- [ ] T021 [US1] `internal/storage/oauth_binding.go`: `encodeOAuthRecord`, `decodeOAuthRecord`, `ErrOAuthTokenUndecryptable`; `putOAuthRecord(bucket, k, key, rec)` with the explicit key parameter, the plaintext→envelope marker write and `putOAuthRecordHook`; `getOAuthRecordTx` takes the key (makes T010, T011 pass) -- [ ] T022 [US2] `internal/storage/bbolt.go`: route the eight raw decode sites (plan D6) through `decodeOAuthRecord`; `SaveOAuthToken` reads first and refuses an undecryptable row; tolerant `ListOAuthTokens`; new `ListOAuthTokenRows`, `OAuthTokenRow` (makes T012, T013 pass) -- [ ] T023 [US2] `internal/storage/manager.go`: `CleanupOrphanedOAuthTokens` keeps and reports undecryptable rows; `Manager` wrappers for `ListOAuthTokenRows` and the sweep; `SealPlaintextOAuthTokens` (collect, then write) + marker key constant in `models.go` (makes T013, T014 pass) +- [x] T020 [US1] `internal/storage/options.go`: `Option`, `WithOAuthTokenKey`; variadic `opts` on `NewBoltDB` and `NewManager`; `BoltDB.oauthKey` +- [x] T021 [US1] `internal/storage/oauth_binding.go`: `encodeOAuthRecord`, `decodeOAuthRecord`, `ErrOAuthTokenUndecryptable`; `putOAuthRecord(bucket, k, key, rec)` with the explicit key parameter, the plaintext→envelope marker write and `putOAuthRecordHook`; `getOAuthRecordTx` takes the key (makes T010, T011 pass) +- [x] T022 [US2] `internal/storage/bbolt.go`: route the eight raw decode sites (plan D6) through `decodeOAuthRecord`; `SaveOAuthToken` reads first and refuses an undecryptable row; tolerant `ListOAuthTokens`; new `ListOAuthTokenRows`, `OAuthTokenRow` (makes T012, T013 pass) +- [x] T023 [US2] `internal/storage/manager.go`: `CleanupOrphanedOAuthTokens` keeps and reports undecryptable rows; `Manager` wrappers for `ListOAuthTokenRows` and the sweep; `SealPlaintextOAuthTokens` (collect, then write) + marker key constant in `models.go` (makes T013, T014 pass) - [ ] T024 [US1] Pass `WithOAuthTokenKey(nil)` at every open site of plan "Open-site inventory" (Phase 3 supplies the key) so T015 passes; no behaviour change yet - [ ] T025 [US1] Make T016 pass (no code expected beyond T021-T023; if it fails, the gap is a missed write path) @@ -58,28 +58,28 @@ ### Tests first -- [ ] T030 [P] [US3] `internal/config/oauth_token_key_test.go`: `ResolveOAuthTokenKey` table (empty → nil; literal; `${file:}` via a temp file; `${env:}`; `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY`; `_FILE`; env beats field; both env → `ErrOAuthTokenKeyBothSet`; unresolvable (missing file, unset env var, absent keyring entry), unusable (oversized, NUL, not a regular file, relative path), empty, malformed key → the four fixed sentences as `*StartupError` with exit 4, plus the both-set and bad-reference errors; only the unresolvable sentence is the one the standalone `auth logout` exception keys on); returned `KeySource` kind for each row and `InDataDir` true for a path under `data_dir` reached through a symlink; a grep over every returned error that it contains neither the temp path nor the key; `Config.Validate` accepts a well-formed reference to a missing file and rejects a malformed reference -- [ ] T031 [P] [US3] `cmd/mcpproxy/oauth_token_key_exit_test.go`: `classifyError` maps each resolution failure to `ExitCodeConfigError` (4) through `errors.As(*config.StartupError)`, with an error message chosen so the string heuristics alone would not match -- [ ] T032 [P] [US3] `internal/runtime/config_hotreload_fields_test.go` (existing canary goes red when the field is added) + `internal/runtime/oauth_token_key_restart_test.go`: editing the field is `RequiresRestart`, `pinRestartGated` keeps the running value, a save after reload writes the reference string unchanged; the key file is deleted after start and an unrelated hot-reload edit still applies +- [x] T030 [P] [US3] `internal/config/oauth_token_key_test.go`: `ResolveOAuthTokenKey` table (empty → nil; literal; `${file:}` via a temp file; `${env:}`; `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY`; `_FILE`; env beats field; both env → `ErrOAuthTokenKeyBothSet`; unresolvable (missing file, unset env var, absent keyring entry), unusable (oversized, NUL, not a regular file, relative path), empty, malformed key → the four fixed sentences as `*StartupError` with exit 4, plus the both-set and bad-reference errors; only the unresolvable sentence is the one the standalone `auth logout` exception keys on); returned `KeySource` kind for each row and `InDataDir` true for a path under `data_dir` reached through a symlink; a grep over every returned error that it contains neither the temp path nor the key; `Config.Validate` accepts a well-formed reference to a missing file and rejects a malformed reference +- [x] T031 [P] [US3] `cmd/mcpproxy/oauth_token_key_exit_test.go`: `classifyError` maps each resolution failure to `ExitCodeConfigError` (4) through `errors.As(*config.StartupError)`, with an error message chosen so the string heuristics alone would not match +- [x] T032 [P] [US3] `internal/runtime/config_hotreload_fields_test.go` (existing canary goes red when the field is added) + `internal/runtime/oauth_token_key_restart_test.go`: editing the field is `RequiresRestart`, `pinRestartGated` keeps the running value, a save after reload writes the reference string unchanged; the key file is deleted after start and an unrelated hot-reload edit still applies - [ ] T033 [P] [US3] `internal/oauth` redaction test: `RedactedConfig` masks a literal key, also with `reveal_secret_headers` on; `${file:}`, `${env:}` and `${keyring:}` references come back verbatim (FR-024); a GET → `/api/v1/config/apply` round trip of the masked document leaves the stored field unchanged; a whitespace-spelled reference such as `${ file:/abs/path}`, which validation accepts, comes back as written while a non-reference is masked (one shared recogniser); no output contains the key value, key bytes or key-source contents (the public key id and key-source metadata are allowed) - [ ] T038 [P] [US3] `cmd/mcpproxy` test: with an unreadable `${file:}` key reference, `upstream list` and `doctor` (socket path) run and exit 0; `call`/`auth login` (storage-open) exit 4 and the DB bytes are unchanged; `db compact` and `db stats` run without resolving the key, also with both environment variables set; standalone `auth logout --server=` with an unresolvable source (missing key file, unset env var, absent keyring entry) still deletes the row, while both env vars set, a bad reference and an unusable (oversized, NUL, not a regular file, relative path), empty or malformed value exit 4 ### Implementation -- [ ] T034 [US3] `internal/config/config.go`: field `OAuthTokenEncryptionKey`; `Validate` does the syntax-only check. `internal/config/oauth_token_key.go`: `ResolveOAuthTokenKey`, `KeySource`, env constants, `ExitCodeOAuthTokenKeyError = 4`, errors as `NewStartupError` (makes T030, T031 pass) -- [ ] T035 [US3] `internal/runtime/config_hotreload.go` `restartGatedConfigFields` + `internal/runtime/restart_gated.go` `pinRestartGated` (makes T032 pass); redaction code (a field-specific rule: literal always masked, references verbatim, including `${file:}`) as T033 requires -- [ ] T036 [US1] Replace the `nil` keys of T024 with the resolved key at every open site; `runtime.New` resolves once before `storage.NewManager` and keeps key + `KeySource`; shared `openStorageForCLI(cfg)` helper in `cmd/mcpproxy`; `internal/upstream/cli/client.go` returns a resolution error instead of falling back to in-memory storage, except for the delete-only standalone `auth logout` path, which opens with a nil key when the key source is missing or unreadable (file absent, env var unset, keyring entry absent); a `NewBoltDB` error after successful resolution keeps the existing fallback (makes T038 pass) -- [ ] T037 [P] [US3] Confirm no Settings row on either side (`fields.ts`, `SettingsCatalog.swift`; `scripts/check-settings-parity.py` needs no change); `make swagger` (`oas/swagger.yaml`, `oas/docs.go`) +- [x] T034 [US3] `internal/config/config.go`: field `OAuthTokenEncryptionKey`; `Validate` does the syntax-only check. `internal/config/oauth_token_key.go`: `ResolveOAuthTokenKey`, `KeySource`, env constants, `ExitCodeOAuthTokenKeyError = 4`, errors as `NewStartupError` (makes T030, T031 pass) +- [x] T035 [US3] `internal/runtime/config_hotreload.go` `restartGatedConfigFields` + `internal/runtime/restart_gated.go` `pinRestartGated` (makes T032 pass); redaction code (a field-specific rule: literal always masked, references verbatim, including `${file:}`) as T033 requires +- [x] T036 [US1] Replace the `nil` keys of T024 with the resolved key at every open site; `runtime.New` resolves once before `storage.NewManager` and keeps key + `KeySource`; shared `openStorageForCLI(cfg)` helper in `cmd/mcpproxy`; `internal/upstream/cli/client.go` returns a resolution error instead of falling back to in-memory storage, except for the delete-only standalone `auth logout` path, which opens with a nil key when the key source is missing or unreadable (file absent, env var unset, keyring entry absent); a `NewBoltDB` error after successful resolution keeps the existing fallback (makes T038 pass) +- [x] T037 [P] [US3] Confirm no Settings row on either side (`fields.ts`, `SettingsCatalog.swift`; `scripts/check-settings-parity.py` needs no change); `make swagger` (`oas/swagger.yaml`, `oas/docs.go`) ## Phase 4: boot sweep, OAuth read paths and health (FR-016, FR-031) ### Tests first -- [ ] T040 [P] [US1] `internal/runtime/oauth_seal_boot_test.go`: with a key and plaintext rows, after `runtime.New` every valid plaintext row is sealed, and a hook asserts the sweep ran (after the shutdown marker is armed) before the upstream manager, the refresh manager and every other OAuth consumer were constructed; a transaction-level sweep failure (fault hook) makes `runtime.New` close storage and return an error -- [ ] T041 [P] [US2] `internal/oauth/persistent_token_store_undecryptable_test.go`: `GetToken` returns the typed error (not `transport.ErrNoToken`); `HasPersistedTokenBound` and `GetPersistedRefreshToken` return it through their new error results; a login (`WithLoginClient` save of token + DCR) against an undecryptable row fails and leaves the bytes; refresh manager `Start` schedules the decodable servers and skips the undecryptable one +- [x] T040 [P] [US1] `internal/runtime/oauth_seal_boot_test.go`: with a key and plaintext rows, after `runtime.New` every valid plaintext row is sealed, and a hook asserts the sweep ran (after the shutdown marker is armed) before the upstream manager, the refresh manager and every other OAuth consumer were constructed; a transaction-level sweep failure (fault hook) makes `runtime.New` close storage and return an error +- [x] T041 [P] [US2] `internal/oauth/persistent_token_store_undecryptable_test.go`: `GetToken` returns the typed error (not `transport.ErrNoToken`); `HasPersistedTokenBound` and `GetPersistedRefreshToken` return it through their new error results; a login (`WithLoginClient` save of token + DCR) against an undecryptable row fails and leaves the bytes; refresh manager `Start` schedules the decodable servers and skips the undecryptable one - [ ] T047 [P] [US2] `internal/upstream` tests over the plan D8 inventory: for each site, an undecryptable row produces the typed error / `OAuthTokenUndecryptable` last error and never starts an OAuth flow (`connection_oauth.go` precheck paths, `client.go:852`, `manager.go:3000`, `manager.go:3547`); plus the read-path inventory source test (fails when a new production caller of `GetOAuthToken*`/`HasPersistedToken*`/`GetPersistedRefreshToken` is not listed) -- [ ] T042 [P] [US2] `internal/health/calculator_oauth_undecryptable_test.go` + runtime server-list test: an undecryptable row yields `unhealthy`, action `configure`, the reason in the detail, code `MCPX_OAUTH_TOKEN_UNDECRYPTABLE`; never `login`, also when the server is connected (anonymous connection, a later call needs authentication); a connected server that needs no login stays healthy and the static-header exclusion still applies -- [ ] T043 [P] [US2] `internal/diagnostics` catalog contract test fails until the new code has a registry entry and `docs/errors/MCPX_OAUTH_TOKEN_UNDECRYPTABLE.md` +- [x] T042 [P] [US2] `internal/health/calculator_oauth_undecryptable_test.go` + runtime server-list test: an undecryptable row yields `unhealthy`, action `configure`, the reason in the detail, code `MCPX_OAUTH_TOKEN_UNDECRYPTABLE`; never `login`, also when the server is connected (anonymous connection, a later call needs authentication); a connected server that needs no login stays healthy and the static-header exclusion still applies +- [x] T043 [P] [US2] `internal/diagnostics` catalog contract test fails until the new code has a registry entry and `docs/errors/MCPX_OAUTH_TOKEN_UNDECRYPTABLE.md` - [ ] T056 [P] [US2] login refusal test (PR-2; the richer pre-flight UX stays in PR-3): `mcpproxy auth login --server=` and the REST login trigger and the connection path against an undecryptable row return `MCPX_OAUTH_TOKEN_UNDECRYPTABLE` and make no HTTP request to the authorization server or DCR endpoint (fixture counts requests) ### Implementation @@ -91,8 +91,8 @@ ## Phase 6a: feature documentation (FR-041, FR-042) -- [ ] T061 [P] [US5] New `docs/features/oauth-token-encryption.md` per plan "Docs plan / PR-2" (including which delivery protects against disk/VM snapshots, i.e. only where the captured storage does not hold the means to recover the key: TPM-bound credential, external secret manager, key on another volume; and which only against copies of `config.db`, notably a host-key-only `LoadCredentialEncrypted=` credential, a plain `LoadCredential=` file and a same-volume Compose secret); add it to `website/sidebars.js` next to `features/oauth-authentication` (the `features/**` glob in `docusaurus.config.js` already publishes it); link it from `docs/features/oauth-authentication.md` -- [ ] T062 [P] [US5] `docs/configuration/config-file.md`, `docs/configuration/environment-variables.md`, `docs/configuration.md` tables +- [x] T061 [P] [US5] New `docs/features/oauth-token-encryption.md` per plan "Docs plan / PR-2" (including which delivery protects against disk/VM snapshots, i.e. only where the captured storage does not hold the means to recover the key: TPM-bound credential, external secret manager, key on another volume; and which only against copies of `config.db`, notably a host-key-only `LoadCredentialEncrypted=` credential, a plain `LoadCredential=` file and a same-volume Compose secret); add it to `website/sidebars.js` next to `features/oauth-authentication` (the `features/**` glob in `docusaurus.config.js` already publishes it); link it from `docs/features/oauth-authentication.md` +- [x] T062 [P] [US5] `docs/configuration/config-file.md`, `docs/configuration/environment-variables.md`, `docs/configuration.md` tables - [ ] T063 [P] [US5] Extend the PR-1 isolation-page and OAuth-page sentences with the encryption condition and the same-user caveat ## PR-3 @@ -101,26 +101,26 @@ ### Tests first -- [ ] T050 [P] [US2] `internal/management/diagnostics_oauth_storage_test.go`: section counts for a mixed bucket form a partition that sums to the row total, with `undecryptable_by_reason`; per-server reasons; warnings `literal_key`, `key_file_in_data_dir`, `plaintext_rows_with_key`, `compaction_advised`, `backup_file_present` computed from the runtime's `KeySource` and data dir; a scoped caller sees only its visible servers and no kid; no output contains key bytes or the reference path -- [ ] T051 [P] [US4] `cmd/mcpproxy/auth_tokens_cmd_test.go`: `status` text and `-o json`; `encrypt` and `--dry-run`; `decrypt --yes` (and refusal without `--yes`); no key → exit 4; locked DB → exit 3; exit 1 when rows remain in the unwanted state; config reference unreadable while `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY_FILE` supplies the key → works; several hundred rows spanning many leaf pages all converted; after `decrypt`, every row decodes with plain `json.Unmarshal` (downgrade simulation) -- [ ] T052 [P] [US1] `cmd/mcpproxy/db_cmd_test.go`: `db compact` with the default `--keep-backup=true` keeps the marker and prints the `config.db.bak` note; `--keep-backup=false` removes the marker; doctor shows `backup_file_present` until the `.bak` is deleted +- [x] T050 [P] [US2] `internal/management/diagnostics_oauth_storage_test.go`: section counts for a mixed bucket form a partition that sums to the row total, with `undecryptable_by_reason`; per-server reasons; warnings `literal_key`, `key_file_in_data_dir`, `plaintext_rows_with_key`, `compaction_advised`, `backup_file_present` computed from the runtime's `KeySource` and data dir; a scoped caller sees only its visible servers and no kid; no output contains key bytes or the reference path +- [x] T051 [P] [US4] `cmd/mcpproxy/auth_tokens_cmd_test.go`: `status` text and `-o json`; `encrypt` and `--dry-run`; `decrypt --yes` (and refusal without `--yes`); no key → exit 4; locked DB → exit 3; exit 1 when rows remain in the unwanted state; config reference unreadable while `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY_FILE` supplies the key → works; several hundred rows spanning many leaf pages all converted; after `decrypt`, every row decodes with plain `json.Unmarshal` (downgrade simulation) +- [x] T052 [P] [US1] `cmd/mcpproxy/db_cmd_test.go`: `db compact` with the default `--keep-backup=true` keeps the marker and prints the `config.db.bak` note; `--keep-backup=false` removes the marker; doctor shows `backup_file_present` until the `.bak` is deleted ### Implementation -- [ ] T053 [US2] `internal/contracts/types.go` `OAuthTokenStorageReport`; runtime accessor (key, `KeySource`, rows, marker, `.bak` presence); `internal/management/diagnostics.go` fill + `RuntimeWarnings`; doctor CLI rendering; `make swagger` (makes T050 pass) -- [ ] T054 [US4] `cmd/mcpproxy/auth_tokens_cmd.go` under `auth`, through `openStorageForCLI` (makes T051 pass) -- [ ] T055 [US1] `cmd/mcpproxy/db_cmd.go` marker handling and note (makes T052 pass) +- [x] T053 [US2] `internal/contracts/types.go` `OAuthTokenStorageReport`; runtime accessor (key, `KeySource`, rows, marker, `.bak` presence); `internal/management/diagnostics.go` fill + `RuntimeWarnings`; doctor CLI rendering; `make swagger` (makes T050 pass) +- [x] T054 [US4] `cmd/mcpproxy/auth_tokens_cmd.go` under `auth`, through `openStorageForCLI` (makes T051 pass) +- [x] T055 [US1] `cmd/mcpproxy/db_cmd.go` marker handling and note (makes T052 pass) ## Phase 6b: surface documentation -- [ ] T064 [P] [US5] `docs/features/oauth-token-encryption.md`: doctor output, downgrade / disable / rotation with the offline key form (plan "Docs plan / PR-3"; rotation = decrypt with the old key, change the key, encrypt, then `db compact --keep-backup=false`, delete any existing `config.db.bak`, warn about copies made during the plaintext interval) -- [ ] T065 [P] [US5] `docs/cli/command-reference.md` (`auth tokens`, the doctor section), `docs/api/rest-api.md` (`oauth_token_storage` in `GET /api/v1/diagnostics`), `docs/cli/db-commands.md` (compaction and backup note) +- [x] T064 [P] [US5] `docs/features/oauth-token-encryption.md`: doctor output, downgrade / disable / rotation with the offline key form (plan "Docs plan / PR-3"; rotation = decrypt with the old key, change the key, encrypt, then `db compact --keep-backup=false`, delete any existing `config.db.bak`, warn about copies made during the plaintext interval) +- [x] T065 [P] [US5] `docs/cli/command-reference.md` (`auth tokens`, the doctor section), `docs/api/rest-api.md` (`oauth_token_storage` in `GET /api/v1/diagnostics`), `docs/cli/db-commands.md` (compaction and backup note) ## Phase 7: verification (PR-2 and PR-3) - [ ] T070 [US1] (PR-2) e2e step with the OAuth test fixture (`oauth-e2e-testing` setup): login with a key → raw scan of `config.db` → restart with the key reference removed (health detail, bytes unchanged) → restart with a missing key file (exit 4, bytes unchanged) → restart with key (authenticated, no browser) (US1, US2, US3, SC-001, SC-002) - [ ] T071 [US1] (PR-2) `BenchmarkGetOAuthToken{Plaintext,Sealed}` mean ns/op and allocs/op recorded in the PR (SC-005, informational) -- [ ] T072 Gates: golangci-lint v2 bare and `--build-tags server`; `go test -race` over the packages in plan "Technical Context" and the CI `-tags server` lane; `./scripts/test-api-e2e.sh`; swagger verify; `scripts/check-settings-parity.py`; `scripts/check-upstream-write-sites.sh` +- [x] T072 Gates: golangci-lint v2 bare and `--build-tags server`; `go test -race` over the packages in plan "Technical Context" and the CI `-tags server` lane; `./scripts/test-api-e2e.sh`; swagger verify; `scripts/check-settings-parity.py`; `scripts/check-upstream-write-sites.sh` - [ ] T073 SC-004 sweep: grep all captured test logs, errors, CLI and REST outputs for the test key bytes, its base64 and the key-file contents; the public key id and key-source metadata are allowed (also assert that `GET /api/v1/secrets/config` reports presence only for a `${env:}` / `${keyring:}` key reference and returns no value, and that daemon key resolution for use happens once; the config file itself intentionally keeps a literal key or the original `${...}` reference; assert only that a save never replaces a reference with resolved key material, that `GET /api/v1/config` masks a literal key even with `reveal_secret_headers` and shows a reference as written; an operator-written `${file:}` path is not a violation, resolved values and key-file contents are) - [ ] T074 Cross-model review rounds per the maintainer's reviewer ladder (crypto + storage change: request the hard-problem reviewer for Phases 1-2) From 102f83cbced07af9dc8f9c0688622b194aaf815e Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 16 Nov 2026 06:23:11 +0000 Subject: [PATCH 08/11] chore(roadmap): regenerate ROADMAP.md after gardener checkbox sync --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 3dc586e94..a44c0ad0d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1205,4 +1205,4 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [119-scan-default-trust](./specs/119-scan-default-trust/) | — | — | | [120-scan-structural-gate](./specs/120-scan-structural-gate/) | — | — | | [122-scanner-skillspector-checks](./specs/122-scanner-skillspector-checks/) | `shipped` | 31/31 (100%) | -| [123-oauth-token-encryption](./specs/123-oauth-token-encryption/) | `drafted` | 0/56 (0%) | +| [123-oauth-token-encryption](./specs/123-oauth-token-encryption/) | `in-flight` | 40/56 (71%) | From 1383f3a3e3d9df91bec8f35e07ff354ab58ccbc5 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 06:19:31 +0000 Subject: [PATCH 09/11] chore(specs): revert stale unverified ticks brought in by merge The previous (closed, unmerged) PR's checkbox ticks for 058, 113, 116 and 123 came back in via the merge from an earlier branch state and were not re-verified in this run. Resetting those four tasks.md files to main's current (unticked) content before applying this run's freshly verified ticks. --- ROADMAP.md | 16 +-- specs/058-mcp-2026-upgrade/tasks.md | 2 +- specs/113-upstream-resilience/tasks.md | 120 +++++++++---------- specs/116-config-commit-consistency/tasks.md | 16 +-- specs/123-oauth-token-encryption/tasks.md | 80 ++++++------- 5 files changed, 117 insertions(+), 117 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 49cc75138..0c1f21f46 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1258,7 +1258,7 @@ graph LR | 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/) | | -| MCP protocol upgrade to 2026-07-28 revision | In progress | P1 | 41/81 (51%) | [058-mcp-2026-upgrade](./specs/058-mcp-2026-upgrade/) | | +| MCP protocol upgrade to 2026-07-28 revision | In progress | P1 | 40/81 (49%) | [058-mcp-2026-upgrade](./specs/058-mcp-2026-upgrade/) | | | Spec 108 profiles v3: scoped profiles, client binding, scope-aware observability | In progress | P1 | 194/195 (99%) | [108-profiles-v3](./specs/108-profiles-v3/) | | | Spec 109 navigation, scope filters and cross-surface UX consistency | In progress | P1 | 257/258 (100%) | [109-ux-navigation-consistency](./specs/109-ux-navigation-consistency/) | | | Spec 124 work sessions and the failure timeline | In progress | P1 | 0/74 (0%) | [124-session-failure-timeline](./specs/124-session-failure-timeline/) | | @@ -1281,7 +1281,7 @@ graph LR | SDK v1 migration | Todo (parked) | P3 | — | | | | Upgrade awareness & guided update | Done | P0 | — | [079-upgrade-nudge](./specs/079-upgrade-nudge/) | | | Connect step trust: preview, visible backup, one-click undo | Done | P0 | — | [078-connect-trust-preview](./specs/078-connect-trust-preview/) | | -| Spec 116 config commit consistency: one commit section, atomic removal, upstream retirement | Done | P0 | 89/124 (72%) | [116-config-commit-consistency](./specs/116-config-commit-consistency/) | #1590 #1600 #1608 #1612 #1621 | +| Spec 116 config commit consistency: one commit section, atomic removal, upstream retirement | Done | P0 | 81/124 (65%) | [116-config-commit-consistency](./specs/116-config-commit-consistency/) | #1590 #1600 #1608 #1612 #1621 | | Spec 117 review-bound approvals: durable baselines, hash-bound approvals, ordered tool inventories | Done | P0 | 46/50 (92%) | [117-review-bound-approvals](./specs/117-review-bound-approvals/) | #1604 #1605 #1609 | | Spec 118 profile pin as the visibility boundary for agent tokens on every REST/SSE read door | Done | P0 | — | [118-pin-visibility-boundary](./specs/118-pin-visibility-boundary/) | #1684 #1688 #1821 | | Spec 119 scan is the default trust mode; a clean-scanned contract change auto-approves | Done | P0 | — | [119-scan-default-trust](./specs/119-scan-default-trust/) | #1740 | @@ -1293,12 +1293,12 @@ graph LR | Scanner simplification (deterministic default, opt-in deep scan) | Done | P1 | 38/42 (90%) | [077-scanner-simplification](./specs/077-scanner-simplification/) | | | Deferred-schema serialization for the direct tools/list surface (spec 102) | Done | P1 | 89/89 (100%) | [102-schema-deferred](./specs/102-schema-deferred/) | #1063 | | Agent-token scope hardening: every MCP request authorized by its own scope (spec 105) | Done | P1 | 111/113 (98%) | [105-agent-scope-hardening](./specs/105-agent-scope-hardening/) | | -| Spec 113 upstream resilience: OAuth refresh, discovery, call-error taxonomy, session re-init | Done | P1 | 60/100 (60%) | [113-upstream-resilience](./specs/113-upstream-resilience/) | #1495 #1498 #1499 #1501 #1502 #1504 #1510 #1650 | +| Spec 113 upstream resilience: OAuth refresh, discovery, call-error taxonomy, session re-init | Done | P1 | 0/100 (0%) | [113-upstream-resilience](./specs/113-upstream-resilience/) | #1495 #1498 #1499 #1501 #1502 #1504 #1510 #1650 | | Spec 115 admin MCP credentials tool: client credentials + agent token lifecycle | Done | P1 | 86/87 (99%) | [115-mcp-credential-lifecycle](./specs/115-mcp-credential-lifecycle/) | #1557 | | Quarantine/approval testing pilot: independent policy model, scenario inventory, mutation gate | Done | P1 | — | | #1619 #1631 #1634 | | Spec 118 automatic rescan after a tool-definition change (clean verdict recorded as hold evidence) | Done | P1 | — | [118-auto-rescan-on-change](./specs/118-auto-rescan-on-change/) | #1689 | | Spec 122 SkillSpector-informed checks for the built-in tool scanner | Done | P1 | 31/31 (100%) | [122-scanner-skillspector-checks](./specs/122-scanner-skillspector-checks/) | #1818 | -| Spec 123 encrypt upstream OAuth tokens at rest (opt-in key, doctor section, auth tokens commands) | Done | P1 | 40/56 (71%) | [123-oauth-token-encryption](./specs/123-oauth-token-encryption/) | #1886 #1887 #1888 #1891 | +| Spec 123 encrypt upstream OAuth tokens at rest (opt-in key, doctor section, auth tokens commands) | Done | P1 | 0/56 (0%) | [123-oauth-token-encryption](./specs/123-oauth-token-encryption/) | #1886 #1887 #1888 #1891 | | Tray↔core decoupling: socket/REST API only, no config-file reads | Done | P2 | — | | | | Spec 107 server edition SSO front door hardened for real IdPs | Done | P2 | 126/126 (100%) | [107-server-edition-sso-hardening](./specs/107-server-edition-sso-hardening/) | | @@ -1380,7 +1380,7 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [055-frontend-major-upgrades](./specs/055-frontend-major-upgrades/) | `shipped` | 23/24 (96%) | | [056-output-schema-validation](./specs/056-output-schema-validation/) | `in-flight` | 22/24 (92%) | | [057-in-proxy-profiles](./specs/057-in-proxy-profiles/) | `in-flight` | 20/25 (80%) | -| [058-mcp-2026-upgrade](./specs/058-mcp-2026-upgrade/) | `in-flight` | 41/81 (51%) | +| [058-mcp-2026-upgrade](./specs/058-mcp-2026-upgrade/) | `in-flight` | 40/81 (49%) | | [059-output-sanitisation](./specs/059-output-sanitisation/) | `shipped` | 24/25 (96%) | | [060-settings-page](./specs/060-settings-page/) | `shipped` | 16/16 (100%) | | [064-glass-cockpit](./specs/064-glass-cockpit/) | — | — | @@ -1428,16 +1428,16 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [110-catalog-popularity](./specs/110-catalog-popularity/) | `in-flight` | 19/23 (83%) | | [111-personal-docker-image](./specs/111-personal-docker-image/) | — | — | | [112-client-header-forwarding](./specs/112-client-header-forwarding/) | `shipped` | 38/40 (95%) | -| [113-upstream-resilience](./specs/113-upstream-resilience/) | `in-flight` | 60/100 (60%) | +| [113-upstream-resilience](./specs/113-upstream-resilience/) | `drafted` | 0/100 (0%) | | [115-mcp-credential-lifecycle](./specs/115-mcp-credential-lifecycle/) | `shipped` | 86/87 (99%) | -| [116-config-commit-consistency](./specs/116-config-commit-consistency/) | `in-flight` | 89/124 (72%) | +| [116-config-commit-consistency](./specs/116-config-commit-consistency/) | `in-flight` | 81/124 (65%) | | [117-review-bound-approvals](./specs/117-review-bound-approvals/) | `in-flight` | 46/50 (92%) | | [118-auto-rescan-on-change](./specs/118-auto-rescan-on-change/) | — | — | | [118-pin-visibility-boundary](./specs/118-pin-visibility-boundary/) | — | — | | [119-scan-default-trust](./specs/119-scan-default-trust/) | — | — | | [120-scan-structural-gate](./specs/120-scan-structural-gate/) | — | — | | [122-scanner-skillspector-checks](./specs/122-scanner-skillspector-checks/) | `shipped` | 31/31 (100%) | -| [123-oauth-token-encryption](./specs/123-oauth-token-encryption/) | `in-flight` | 40/56 (71%) | +| [123-oauth-token-encryption](./specs/123-oauth-token-encryption/) | `drafted` | 0/56 (0%) | | [124-session-failure-timeline](./specs/124-session-failure-timeline/) | `drafted` | 0/74 (0%) | | [125-skills-over-mcp](./specs/125-skills-over-mcp/) | `shipped` | 51/51 (100%) | | [127-profile-argument-rules](./specs/127-profile-argument-rules/) | — | — | diff --git a/specs/058-mcp-2026-upgrade/tasks.md b/specs/058-mcp-2026-upgrade/tasks.md index 27200a864..b98680c56 100644 --- a/specs/058-mcp-2026-upgrade/tasks.md +++ b/specs/058-mcp-2026-upgrade/tasks.md @@ -155,7 +155,7 @@ Single Go project. Backend paths are repo-relative: `internal/`, `cmd/`, `bench/ - [x] T063 [P] [US5] Write failing tests that list/read responses carry `ttlMs` and an identity-appropriate `cacheScope`, in `internal/server/cache_hints_test.go` - [x] T064 [US5] Configure cache hints — private for identity-scoped surfaces, public for shared ones — in `internal/server/mcp_routing.go` and `internal/server/mcp.go` -- [x] T065 [P] [US5] Write a failing test that repeated `tools/list` calls are byte-identical under unchanged state, in `internal/server/stateless_list_test.go` +- [ ] T065 [P] [US5] Write a failing test that repeated `tools/list` calls are byte-identical under unchanged state, in `internal/server/stateless_list_test.go` - [ ] T066 [US5] Make tool ordering deterministic wherever map iteration currently leaks in, in `internal/server/mcp_routing.go` - [ ] T067 [P] [US5] Write a failing test that external `$ref`s are not dereferenced and that schemas validate as JSON Schema 2020-12, in `internal/server/mcp_input_validation_test.go` - [ ] T068 [US5] Install a rejecting loader so no external `$ref` is fetched, and confirm the dialect default, in `internal/server/mcp_input_validation.go` diff --git a/specs/113-upstream-resilience/tasks.md b/specs/113-upstream-resilience/tasks.md index fde4a6a92..4eec10b78 100644 --- a/specs/113-upstream-resilience/tasks.md +++ b/specs/113-upstream-resilience/tasks.md @@ -10,25 +10,25 @@ Format: `[ID] [P?] [Story] Description (files) — FR`. `[P]` = can run in paral ## Slice 113-a — oauth-refresh-robustness (US1, G1+G2) — T100–T129 -- [x] T100 [P] [US1] Failing test: `ClassifyRefreshError` table — `OAuthError{invalid_grant}` wrapped by mcp-go (`%w`), 200-with-error-body form, `invalid_client`, `unauthorized_client`, `unsupported_grant_type`, `invalid_scope`, mcp-go `"refresh token request failed with status 503: "`, 429, `*net.OpError` dial/reset, `context.DeadlineExceeded`, `server not found`, `server does not use OAuth`, unknown; plus the manual-path typed error (`internal/oauth/refresh_errors_test.go`) — FR-007, FR-008 -- [x] T101 [US1] Implement `ClassifyRefreshError` + `RefreshHTTPError`; derive the existing metric labels from it; keep the substring list only as the last fallback (`internal/oauth/refresh_errors.go`, `refresh_manager.go`) — FR-007, FR-008 -- [x] T102 [P] [US1] Failing test: storage `UpdateOAuthToken(key, mutate)` preserves `ClientID/ClientSecret/CallbackPort/RedirectURI/Created/DisplayName` when `UpdateOAuthClientCredentials` runs concurrently (100 interleaved goroutines, `-race`) (`internal/storage/bbolt_oauth_update_test.go`) — FR-006 -- [x] T103 [US1] Implement `BoltDB.UpdateOAuthToken`; switch `PersistentTokenStore.SaveToken` and the manual refresh path to it (`internal/storage/bbolt.go`, `internal/oauth/persistent_token_store.go`, `internal/upstream/core/client.go`) — FR-006 -- [x] T104 [P] [US1] Failing test: coordinator — N=50 barrier-started `Do` calls on one key run `fn` once and all get the same token; a caller whose observed RT is stale gets the persisted token with `skipped=true` and no `fn` call; a failing `fn` returns the same error to all waiters; a cancelled initiator does not cancel the flight; different keys run in parallel (`internal/oauth/refresh_coordinator_test.go`) — FR-001, FR-003, FR-004 -- [x] T105 [US1] Implement `RefreshCoordinator` (`internal/oauth/refresh_coordinator.go`) — FR-001, FR-003, FR-004, FR-011 -- [x] T106 [P] [US1] Failing test: `PersistentTokenStore.GetToken` with a bound refresher and an expired token refreshes through the coordinator and returns the new token; without a bound refresher it never calls the network (assert on an `httptest` AS request counter); terminal error wraps `transport.ErrOAuthAuthorizationRequired`; transient returns `ErrTokenRefreshTransient` (`internal/oauth/persistent_token_store_test.go`) — FR-002, FR-005 -- [x] T107 [US1] Implement refresher binding: `SetRefresher`/`BindRefreshHandler` with an `atomic.Pointer` handler slot; `GetToken` pre-emption; `SaveToken` never enters the coordinator (`internal/oauth/persistent_token_store.go`, `internal/oauth/config.go` attach, `internal/upstream/core/connection_oauth.go` bind call) — FR-002, FR-005 -- [x] T108 [US1] Route `RefreshOAuthTokenDirect` (both sub-paths) through the coordinator with trigger `proactive`; manual path returns `RefreshHTTPError` (`internal/upstream/core/client.go`, `internal/upstream/manager.go`) — FR-001, FR-007 -- [x] T109 [P] [US1] Failing test (SC-001): rotating `httptest` AS that revokes the grant on refresh-token reuse; expired token; 50 goroutines through a real mcp-go `StreamableHTTP` client with OAuth against an `httptest` MCP server + 1 concurrent `RefreshOAuthTokenDirect`; assert exactly 1 token request, all calls succeed; `-race -count=20` (`internal/upstream/core/oauth_refresh_race_test.go`) — FR-012, SC-001 -- [x] T110 [P] [US1] Failing test: `invalid_client` with a DCR record → `ClearOAuthClientCredentials` called once, schedule `RefreshStateFailed` with the re-register message, zero further retries; second `invalid_client` after a re-registration and before any success → terminal "rejects new registrations"; static client → terminal, credentials untouched; a registration or grant saved by a concurrent login is not cleared (compare-and-clear) (`internal/oauth/refresh_manager_invalid_client_test.go`) — FR-009, SC-002 -- [x] T111 [US1] Implement `invalid_client` handling and per-key re-registration state (`internal/oauth/refresh_manager.go`, `refresh_coordinator.go`) — FR-009 -- [x] T112 [P] [US1] Failing test: `RefreshManager` reads records by server key (token-age log and `EmitOAuthTokenRefreshed` fire for a keyed record) (`internal/oauth/refresh_manager_test.go`) — FR-010 -- [x] T113 [US1] Fix the two `GetOAuthToken(serverName)` lookups to use the server key (needs the server URL: obtain via the runtime interface or store the key on the schedule) (`internal/oauth/refresh_manager.go`) — FR-010 -- [x] T114 [US1] CLI in-memory store path uses the same coordinator (`internal/oauth/config.go` `globalTokenStoreManager`) + test — FR-014 -- [x] T119 [P] [US1] Failing test: bound store returns `ExpiresAt` zero to mcp-go and mcp-go never issues a refresh even when the token expires between `GetToken` and `IsExpired`; reactive refresh with a DCR record and a handler lacking a client id uses stored credentials; terminal latch (no network after `invalid_grant` until a new token is saved) and transient cooldown; compare-and-clear does not clear a registration saved by a concurrent login; login-flow `invalid_client` after re-registration is terminal (`internal/oauth/refresh_coordinator_test.go`, `internal/upstream/core/oauth_refresh_race_test.go`) — FR-002, FR-003, FR-004, FR-009 -- [x] T120 [P] [US1] Failing test: login saves a new token and DCR client while an old refresh flight is in flight; the old flight's success is discarded (login token kept, client/token pair consistent) and its `invalid_grant` failure neither latches nor fails the schedule (`internal/oauth/refresh_coordinator_test.go`) — FR-006a +- [ ] T100 [P] [US1] Failing test: `ClassifyRefreshError` table — `OAuthError{invalid_grant}` wrapped by mcp-go (`%w`), 200-with-error-body form, `invalid_client`, `unauthorized_client`, `unsupported_grant_type`, `invalid_scope`, mcp-go `"refresh token request failed with status 503: "`, 429, `*net.OpError` dial/reset, `context.DeadlineExceeded`, `server not found`, `server does not use OAuth`, unknown; plus the manual-path typed error (`internal/oauth/refresh_errors_test.go`) — FR-007, FR-008 +- [ ] T101 [US1] Implement `ClassifyRefreshError` + `RefreshHTTPError`; derive the existing metric labels from it; keep the substring list only as the last fallback (`internal/oauth/refresh_errors.go`, `refresh_manager.go`) — FR-007, FR-008 +- [ ] T102 [P] [US1] Failing test: storage `UpdateOAuthToken(key, mutate)` preserves `ClientID/ClientSecret/CallbackPort/RedirectURI/Created/DisplayName` when `UpdateOAuthClientCredentials` runs concurrently (100 interleaved goroutines, `-race`) (`internal/storage/bbolt_oauth_update_test.go`) — FR-006 +- [ ] T103 [US1] Implement `BoltDB.UpdateOAuthToken`; switch `PersistentTokenStore.SaveToken` and the manual refresh path to it (`internal/storage/bbolt.go`, `internal/oauth/persistent_token_store.go`, `internal/upstream/core/client.go`) — FR-006 +- [ ] T104 [P] [US1] Failing test: coordinator — N=50 barrier-started `Do` calls on one key run `fn` once and all get the same token; a caller whose observed RT is stale gets the persisted token with `skipped=true` and no `fn` call; a failing `fn` returns the same error to all waiters; a cancelled initiator does not cancel the flight; different keys run in parallel (`internal/oauth/refresh_coordinator_test.go`) — FR-001, FR-003, FR-004 +- [ ] T105 [US1] Implement `RefreshCoordinator` (`internal/oauth/refresh_coordinator.go`) — FR-001, FR-003, FR-004, FR-011 +- [ ] T106 [P] [US1] Failing test: `PersistentTokenStore.GetToken` with a bound refresher and an expired token refreshes through the coordinator and returns the new token; without a bound refresher it never calls the network (assert on an `httptest` AS request counter); terminal error wraps `transport.ErrOAuthAuthorizationRequired`; transient returns `ErrTokenRefreshTransient` (`internal/oauth/persistent_token_store_test.go`) — FR-002, FR-005 +- [ ] T107 [US1] Implement refresher binding: `SetRefresher`/`BindRefreshHandler` with an `atomic.Pointer` handler slot; `GetToken` pre-emption; `SaveToken` never enters the coordinator (`internal/oauth/persistent_token_store.go`, `internal/oauth/config.go` attach, `internal/upstream/core/connection_oauth.go` bind call) — FR-002, FR-005 +- [ ] T108 [US1] Route `RefreshOAuthTokenDirect` (both sub-paths) through the coordinator with trigger `proactive`; manual path returns `RefreshHTTPError` (`internal/upstream/core/client.go`, `internal/upstream/manager.go`) — FR-001, FR-007 +- [ ] T109 [P] [US1] Failing test (SC-001): rotating `httptest` AS that revokes the grant on refresh-token reuse; expired token; 50 goroutines through a real mcp-go `StreamableHTTP` client with OAuth against an `httptest` MCP server + 1 concurrent `RefreshOAuthTokenDirect`; assert exactly 1 token request, all calls succeed; `-race -count=20` (`internal/upstream/core/oauth_refresh_race_test.go`) — FR-012, SC-001 +- [ ] T110 [P] [US1] Failing test: `invalid_client` with a DCR record → `ClearOAuthClientCredentials` called once, schedule `RefreshStateFailed` with the re-register message, zero further retries; second `invalid_client` after a re-registration and before any success → terminal "rejects new registrations"; static client → terminal, credentials untouched; a registration or grant saved by a concurrent login is not cleared (compare-and-clear) (`internal/oauth/refresh_manager_invalid_client_test.go`) — FR-009, SC-002 +- [ ] T111 [US1] Implement `invalid_client` handling and per-key re-registration state (`internal/oauth/refresh_manager.go`, `refresh_coordinator.go`) — FR-009 +- [ ] T112 [P] [US1] Failing test: `RefreshManager` reads records by server key (token-age log and `EmitOAuthTokenRefreshed` fire for a keyed record) (`internal/oauth/refresh_manager_test.go`) — FR-010 +- [ ] T113 [US1] Fix the two `GetOAuthToken(serverName)` lookups to use the server key (needs the server URL: obtain via the runtime interface or store the key on the schedule) (`internal/oauth/refresh_manager.go`) — FR-010 +- [ ] T114 [US1] CLI in-memory store path uses the same coordinator (`internal/oauth/config.go` `globalTokenStoreManager`) + test — FR-014 +- [ ] T119 [P] [US1] Failing test: bound store returns `ExpiresAt` zero to mcp-go and mcp-go never issues a refresh even when the token expires between `GetToken` and `IsExpired`; reactive refresh with a DCR record and a handler lacking a client id uses stored credentials; terminal latch (no network after `invalid_grant` until a new token is saved) and transient cooldown; compare-and-clear does not clear a registration saved by a concurrent login; login-flow `invalid_client` after re-registration is terminal (`internal/oauth/refresh_coordinator_test.go`, `internal/upstream/core/oauth_refresh_race_test.go`) — FR-002, FR-003, FR-004, FR-009 +- [ ] T120 [P] [US1] Failing test: login saves a new token and DCR client while an old refresh flight is in flight; the old flight's success is discarded (login token kept, client/token pair consistent) and its `invalid_grant` failure neither latches nor fails the schedule (`internal/oauth/refresh_coordinator_test.go`) — FR-006a - [ ] T115 [US1] 5xx/429/network → existing backoff with `failed_server_error`/`failed_network` labels; test asserts backoff sequence unchanged — FR-008, FR-013 -- [x] T116 Docs: `docs/oauth-resource-autodetect.md` or the OAuth troubleshooting page — refresh serialization, `invalid_client` behaviour, new metric labels (published-site rules apply) +- [ ] T116 Docs: `docs/oauth-resource-autodetect.md` or the OAuth troubleshooting page — refresh serialization, `invalid_client` behaviour, new metric labels (published-site rules apply) - [ ] T117 Gates: race tests, server-tag tests (CI skip regex), golangci-lint v2 ×2, `./scripts/test-api-e2e.sh` (isolated instance) - [ ] T118 Cross-model review (opencode harness, gpt-6.1-sol), ≤10 rounds - T121–T129 reserved for 113-a follow-ups @@ -36,58 +36,58 @@ Format: `[ID] [P?] [Story] Description (files) — FR`. `[P]` = can run in paral ## Slice 113-b — oauth-discovery-overrides (US2, G3+G5) — T130–T159 - [ ] T130 [P] [US2] Failing test: `OAuthConfig` new fields JSON/mapstructure round-trip, `OAuthConfigChanged` detects each, `MergeOAuthConfig` merges each, storage `UpstreamRecord` round-trip (`internal/config/*_test.go`, `internal/storage/*_test.go`) — FR-022, FR-028, FR-029 -- [x] T131 [US2] Add the four fields; update `OAuthConfigChanged`, `MergeOAuthConfig`, `copyOAuthConfig` (`internal/config/config.go`, `merge.go`) — FR-022, FR-028 -- [x] T132 [P] [US2] Failing test: validation table — https ok; http loopback (`localhost`, `127.0.0.5`, `[::1]`) ok; http public host rejected; relative, fragment, userinfo, empty host rejected; load path drops invalid with Warn and boot succeeds (`internal/config/oauth_validation_test.go`) — FR-023 -- [x] T133 [US2] Implement write-time validation (`ValidateDetailed`, REST, MCP `upstream_servers`, CLI) and load-time sanitize (`internal/config/oauth_validation.go`, write paths) — FR-023 -- [x] T134 [P] [US2] Failing test: `OAuthTransportWrapper` rewrites AS metadata fields from overrides, output passes mcp-go URL validation; synthesizes a document when metadata is unreachable and authz+token overrides exist; leaves non-metadata responses untouched (`internal/oauth/transport_wrapper_test.go`) — FR-024 -- [x] T135 [US2] Implement metadata rewrite/synthesis in the wrapper; pass `auth_server_metadata_url` to `OAuthConfig.AuthServerMetadataURL` (`internal/oauth/transport_wrapper.go`, `internal/oauth/config.go`) — FR-024 +- [ ] T131 [US2] Add the four fields; update `OAuthConfigChanged`, `MergeOAuthConfig`, `copyOAuthConfig` (`internal/config/config.go`, `merge.go`) — FR-022, FR-028 +- [ ] T132 [P] [US2] Failing test: validation table — https ok; http loopback (`localhost`, `127.0.0.5`, `[::1]`) ok; http public host rejected; relative, fragment, userinfo, empty host rejected; load path drops invalid with Warn and boot succeeds (`internal/config/oauth_validation_test.go`) — FR-023 +- [ ] T133 [US2] Implement write-time validation (`ValidateDetailed`, REST, MCP `upstream_servers`, CLI) and load-time sanitize (`internal/config/oauth_validation.go`, write paths) — FR-023 +- [ ] T134 [P] [US2] Failing test: `OAuthTransportWrapper` rewrites AS metadata fields from overrides, output passes mcp-go URL validation; synthesizes a document when metadata is unreachable and authz+token overrides exist; leaves non-metadata responses untouched (`internal/oauth/transport_wrapper_test.go`) — FR-024 +- [ ] T135 [US2] Implement metadata rewrite/synthesis in the wrapper; pass `auth_server_metadata_url` to `OAuthConfig.AuthServerMetadataURL` (`internal/oauth/transport_wrapper.go`, `internal/oauth/config.go`) — FR-024 - [ ] T136 [P] [US2] Failing test: `extra_params` injected on a token endpoint `/oauth2/v1/exchange` learned from metadata; not on `/api/tokens/list`; heuristic still used when no endpoint known; 201→200 normalization follows the same match (`transport_wrapper_test.go`) — FR-025 -- [x] T137 [US2] Implement endpoint-URL matching (`internal/oauth/transport_wrapper.go`) — FR-025 +- [ ] T137 [US2] Implement endpoint-URL matching (`internal/oauth/transport_wrapper.go`) — FR-025 - [ ] T138 [P] [US2] Failing test: end-to-end with `httptest` AS on a non-standard metadata path + override; mcp-go authorization URL host equals override; token exchange and refresh hit the override (`internal/upstream/core/oauth_overrides_test.go`) — FR-024, FR-031 -- [x] T139 [P] [US2] Failing test: discovery cache — 5 `createOAuthConfigInternal` calls → 1 request per discovery URL; different overrides → separate entries; failure cached 30 s then retried; LRU bound; invalidation on a differing `resource_metadata` (`internal/oauth/discovery_cache_test.go`) — FR-026, FR-027, SC-003 -- [x] T140 [US2] Implement `discovery_cache.go` and route preflight discovery through it; invalidation hook from the 401 PRM-URL handling (`internal/oauth/discovery.go`, `discovery_cache.go`, `config.go`, `internal/upstream/core/connection.go` one call) — FR-026, FR-027 -- [x] T141 [P] [US2] Failing test: scope waterfall — PRM scopes + AS advertises `offline_access` → appended once; explicit `oauth.scopes` → unchanged; AS-derived scopes → unchanged; empty → unchanged (`internal/oauth/config_test.go`) — FR-020 -- [x] T142 [US2] Implement `offline_access` append (`internal/oauth/config.go`) — FR-020 -- [x] T143 [P] [US2] Failing test: `grant_types_supported` without `refresh_token` → one Warn per server per process (zap observer); absent field → none (`internal/oauth/discovery_test.go`) — FR-021 -- [x] T144 [US2] Implement the warning (`internal/oauth/discovery.go` or `config.go`) — FR-021 +- [ ] T139 [P] [US2] Failing test: discovery cache — 5 `createOAuthConfigInternal` calls → 1 request per discovery URL; different overrides → separate entries; failure cached 30 s then retried; LRU bound; invalidation on a differing `resource_metadata` (`internal/oauth/discovery_cache_test.go`) — FR-026, FR-027, SC-003 +- [ ] T140 [US2] Implement `discovery_cache.go` and route preflight discovery through it; invalidation hook from the 401 PRM-URL handling (`internal/oauth/discovery.go`, `discovery_cache.go`, `config.go`, `internal/upstream/core/connection.go` one call) — FR-026, FR-027 +- [ ] T141 [P] [US2] Failing test: scope waterfall — PRM scopes + AS advertises `offline_access` → appended once; explicit `oauth.scopes` → unchanged; AS-derived scopes → unchanged; empty → unchanged (`internal/oauth/config_test.go`) — FR-020 +- [ ] T142 [US2] Implement `offline_access` append (`internal/oauth/config.go`) — FR-020 +- [ ] T143 [P] [US2] Failing test: `grant_types_supported` without `refresh_token` → one Warn per server per process (zap observer); absent field → none (`internal/oauth/discovery_test.go`) — FR-021 +- [ ] T144 [US2] Implement the warning (`internal/oauth/discovery.go` or `config.go`) — FR-021 - [ ] T145 [US2] `ServerFieldMaskDecisions` rows `NotSecret` for the four fields; contracts OAuth projection; `cmd/generate-types` + regenerate `frontend/src/types/contracts.ts`; `make swagger`, commit `oas/` — FR-028 -- [x] T150 [P] [US2] Failing test: OAuth client refuses https→http redirect to a non-loopback host and cross-origin redirect of a token/registration POST; same-origin redirect still works; with endpoint overrides and unreachable standard metadata mcp-go never hits `/authorize`, `/token`, `/register` defaults; override with a query string rejected at write time (`internal/oauth/transport_wrapper_test.go`, `internal/config/oauth_validation_test.go`) — FR-023, FR-024, FR-027a +- [ ] T150 [P] [US2] Failing test: OAuth client refuses https→http redirect to a non-loopback host and cross-origin redirect of a token/registration POST; same-origin redirect still works; with endpoint overrides and unreachable standard metadata mcp-go never hits `/authorize`, `/token`, `/register` defaults; override with a query string rejected at write time (`internal/oauth/transport_wrapper_test.go`, `internal/config/oauth_validation_test.go`) — FR-023, FR-024, FR-027a - [ ] T146 [US2] `logSafeURL` everywhere a new URL is logged; test asserts no query string in logs (`internal/oauth`) — FR-030 -- [x] T147 Docs: `docs/configuration.md` OAuth section (four fields, validation, precedence over discovery, `offline_access` rule, cache TTLs) +- [ ] T147 Docs: `docs/configuration.md` OAuth section (four fields, validation, precedence over discovery, `offline_access` rule, cache TTLs) - [ ] T148 Gates (as T117) incl. server-tag build - [ ] T149 Cross-model review (opencode harness, gpt-6.1-sol), ≤10 rounds - T151–T159 reserved for 113-b follow-ups ## Slice 113-c — call-error-taxonomy (US3, G6) — T160–T189 -- [x] T160 [P] [US3] Failing test: `callerr.Classify` table covering every FR-041 rule incl. `isError`, `ErrSessionTerminated`, `OAuthAuthorizationRequiredError`, recorded 401/403, `limiter.LimitError`, `managed.ErrConnectionGenerationChanged`, profile refusal, `jsonschema.ValidationError`, caller `context.Canceled`, `DeadlineExceeded` dispatched vs not, `*net.OpError`, mcp-go `*transport.Error`, recorded 502 with untyped mcp-go error, mcp-go `ErrInvalidParams`/`ErrInternalError`, `errors.New("custom -32001 message")` after a recorded 200, unknown (`internal/callerr/classify_test.go`) — FR-040, FR-041, FR-049 +- [ ] T160 [P] [US3] Failing test: `callerr.Classify` table covering every FR-041 rule incl. `isError`, `ErrSessionTerminated`, `OAuthAuthorizationRequiredError`, recorded 401/403, `limiter.LimitError`, `managed.ErrConnectionGenerationChanged`, profile refusal, `jsonschema.ValidationError`, caller `context.Canceled`, `DeadlineExceeded` dispatched vs not, `*net.OpError`, mcp-go `*transport.Error`, recorded 502 with untyped mcp-go error, mcp-go `ErrInvalidParams`/`ErrInternalError`, `errors.New("custom -32001 message")` after a recorded 200, unknown (`internal/callerr/classify_test.go`) — FR-040, FR-041, FR-049 - [ ] T161 [US3] Implement `internal/callerr` — FR-040, FR-041 -- [x] T162 [P] [US3] Failing test: `Outcome.AuditClass()` total mapping table (`internal/callerr/audit_test.go`) — FR-047 -- [x] T163 [US3] Implement mapping; `audit_funnel.go` uses it so audit and activity agree (`internal/callerr`, `internal/server/audit_funnel.go`) — FR-047 -- [x] T164 [P] [US3] Failing test: transport call recorder — status recorded for the request carrying the recorder ctx only; installed in every `CreateHTTPClient` branch (plain, static headers, trace, Retry-After, OAuth); concurrent calls do not cross-contaminate (`internal/transport/call_recorder_test.go`) — FR-042 +- [ ] T162 [P] [US3] Failing test: `Outcome.AuditClass()` total mapping table (`internal/callerr/audit_test.go`) — FR-047 +- [ ] T163 [US3] Implement mapping; `audit_funnel.go` uses it so audit and activity agree (`internal/callerr`, `internal/server/audit_funnel.go`) — FR-047 +- [ ] T164 [P] [US3] Failing test: transport call recorder — status recorded for the request carrying the recorder ctx only; installed in every `CreateHTTPClient` branch (plain, static headers, trace, Retry-After, OAuth); concurrent calls do not cross-contaminate (`internal/transport/call_recorder_test.go`) — FR-042 - [ ] T165 [US3] Implement `WithCallRecorder` + round-tripper; install in `CreateHTTPClient` (`internal/transport/`) — FR-042 -- [x] T166 [P] [US3] Failing test: `ActivityRecord` new fields omitempty; a pre-Spec-113 JSON fixture decodes byte-identically on re-encode (`internal/storage/activity_models_test.go`) — FR-043 -- [x] T167 [US3] Add fields (`internal/storage/activity_models.go`) — FR-043 -- [x] T168 [US3] Stamp fields at every tool-call activity write path (direct, `call_tool_*`, `code_execution` sub-calls, REST `/api/v1/tools/call`); recorder ctx installed at those dispatch sites (`internal/server/mcp.go`, `mcp_routing.go`, `mcp_code_execution.go`, `server.go`) — FR-044, FR-048 -- [x] T169 [P] [US3] Failing integration test (SC-004): `httptest` Streamable HTTP upstream producing isError, 502 HTML, JSON-RPC -32001, reset, timeout, 404 session, 401; assert persisted record and `GET /api/v1/activity` JSON per class (`internal/server/call_error_taxonomy_test.go`) — SC-004 -- [x] T170 [US3] REST + SSE + contracts + `cmd/generate-types`; `ActivityFilter` `error_class`/`fault_domain`; `make swagger`, commit `oas/` (`internal/contracts/activity.go`, `internal/httpapi/activity.go`, `internal/runtime/activity_service.go`, `event_bus.go`) — FR-045, FR-046 -- [x] T171 [US3] CLI: `activity list|show -o json|yaml` fields; `--error-class`, `--fault-domain`; `activity show` table line (`cmd/mcpproxy/activity_cmd.go` + tests) — FR-045, FR-046 -- [x] T172 Docs: `docs/features/activity-log.md` + `docs/cli/activity-commands.md` (class table, fault domains, filters) +- [ ] T166 [P] [US3] Failing test: `ActivityRecord` new fields omitempty; a pre-Spec-113 JSON fixture decodes byte-identically on re-encode (`internal/storage/activity_models_test.go`) — FR-043 +- [ ] T167 [US3] Add fields (`internal/storage/activity_models.go`) — FR-043 +- [ ] T168 [US3] Stamp fields at every tool-call activity write path (direct, `call_tool_*`, `code_execution` sub-calls, REST `/api/v1/tools/call`); recorder ctx installed at those dispatch sites (`internal/server/mcp.go`, `mcp_routing.go`, `mcp_code_execution.go`, `server.go`) — FR-044, FR-048 +- [ ] T169 [P] [US3] Failing integration test (SC-004): `httptest` Streamable HTTP upstream producing isError, 502 HTML, JSON-RPC -32001, reset, timeout, 404 session, 401; assert persisted record and `GET /api/v1/activity` JSON per class (`internal/server/call_error_taxonomy_test.go`) — SC-004 +- [ ] T170 [US3] REST + SSE + contracts + `cmd/generate-types`; `ActivityFilter` `error_class`/`fault_domain`; `make swagger`, commit `oas/` (`internal/contracts/activity.go`, `internal/httpapi/activity.go`, `internal/runtime/activity_service.go`, `event_bus.go`) — FR-045, FR-046 +- [ ] T171 [US3] CLI: `activity list|show -o json|yaml` fields; `--error-class`, `--fault-domain`; `activity show` table line (`cmd/mcpproxy/activity_cmd.go` + tests) — FR-045, FR-046 +- [ ] T172 Docs: `docs/features/activity-log.md` + `docs/cli/activity-commands.md` (class table, fault domains, filters) - [ ] T173 Gates (as T117) - [ ] T174 Cross-model review (opencode harness, gpt-6.1-sol), ≤10 rounds - T175–T189 reserved for 113-c follow-ups ## Slice 113-d — health-call-failure-rate (US4, G7) — T190–T219 -- [x] T190 [P] [US4] Failing test: `callstats.Window` with injected clock — bucket rotation, 5 min expiry, counted vs uncounted, dominant kind, concurrent `Record` under `-race` (`internal/upstream/callstats/window_test.go`) — FR-060, FR-066 +- [ ] T190 [P] [US4] Failing test: `callstats.Window` with injected clock — bucket rotation, 5 min expiry, counted vs uncounted, dominant kind, concurrent `Record` under `-race` (`internal/upstream/callstats/window_test.go`) — FR-060, FR-066 - [ ] T191 [US4] Implement `Window`, `Registry` (drop on remove/rename) (`internal/upstream/callstats/`) — FR-060, FR-066 -- [x] T192 [P] [US4] Failing test: local predicate table (or 113-c classifier if merged) — isError, policy refusal, limiter, generation refusal, validation, cancel, auth → uncounted; network, post-dispatch timeout, 5xx, JSON-RPC error → failure; success → counted ok (`internal/upstream/callstats/classify_test.go`) — FR-061 -- [x] T193 [US4] Implement predicate (`internal/upstream/callstats/classify.go`) — FR-061 -- [x] T194 [P] [US4] Failing test: both choke points record — `Manager.CallTool`/`CallToolOnEpoch` and `code_execution` dispatch (`internal/upstream/manager_callstats_test.go`, `internal/server/mcp_code_execution_callstats_test.go`) — FR-062 -- [x] T195 [US4] Record in `Manager.callTool` and after `CallToolOnEpoch` in `mcp_code_execution.go`; expose `Manager.CallStats(server)` and `RecordCallOutcome` (`internal/upstream/manager.go`, `internal/server/mcp_code_execution.go`) — FR-062 -- [x] T196 [P] [US4] Failing test: calculator precedence and boundaries table (quarantined, disabled, disconnected, error, OAuth expired, refresh failed, missing secret, retry stopped each win; 4/4 → healthy; 5 @ 50% → healthy; 5 @ 60% → degraded; summary text) (`internal/health/calculator_test.go`) — FR-063, FR-064, FR-067 -- [x] T197 [US4] Add `CallsInWindow`, `CallFailuresInWindow` and the degraded branch with constants (`internal/health/calculator.go`) — FR-063, FR-064, FR-065 -- [x] T198 [US4] Fill the inputs at all three construction sites from `Manager.CallStats` (`internal/runtime/runtime.go`, `internal/server/server.go`, `internal/server/mcp.go`) + a test that the three agree — FR-063 +- [ ] T192 [P] [US4] Failing test: local predicate table (or 113-c classifier if merged) — isError, policy refusal, limiter, generation refusal, validation, cancel, auth → uncounted; network, post-dispatch timeout, 5xx, JSON-RPC error → failure; success → counted ok (`internal/upstream/callstats/classify_test.go`) — FR-061 +- [ ] T193 [US4] Implement predicate (`internal/upstream/callstats/classify.go`) — FR-061 +- [ ] T194 [P] [US4] Failing test: both choke points record — `Manager.CallTool`/`CallToolOnEpoch` and `code_execution` dispatch (`internal/upstream/manager_callstats_test.go`, `internal/server/mcp_code_execution_callstats_test.go`) — FR-062 +- [ ] T195 [US4] Record in `Manager.callTool` and after `CallToolOnEpoch` in `mcp_code_execution.go`; expose `Manager.CallStats(server)` and `RecordCallOutcome` (`internal/upstream/manager.go`, `internal/server/mcp_code_execution.go`) — FR-062 +- [ ] T196 [P] [US4] Failing test: calculator precedence and boundaries table (quarantined, disabled, disconnected, error, OAuth expired, refresh failed, missing secret, retry stopped each win; 4/4 → healthy; 5 @ 50% → healthy; 5 @ 60% → degraded; summary text) (`internal/health/calculator_test.go`) — FR-063, FR-064, FR-067 +- [ ] T197 [US4] Add `CallsInWindow`, `CallFailuresInWindow` and the degraded branch with constants (`internal/health/calculator.go`) — FR-063, FR-064, FR-065 +- [ ] T198 [US4] Fill the inputs at all three construction sites from `Manager.CallStats` (`internal/runtime/runtime.go`, `internal/server/server.go`, `internal/server/mcp.go`) + a test that the three agree — FR-063 - [ ] T199 [US4] Health-change SSE: verify the existing poll/diff emits on a failure-rate change; add debounce only if a push path is needed (record which in the PR) — FR-068 - [ ] T200 [P] [US4] Integration test (SC-005): `httptest` upstream failing 6/10 → `/api/v1/servers` health degraded; advance clock past window → healthy — SC-005 - [ ] T201 Docs: health status page (`docs/` health section) — new degraded reason, thresholds @@ -97,14 +97,14 @@ Format: `[ID] [P?] [Story] Description (files) — FR`. `[P]` = can run in paral ## Slice 113-e — session-terminated-reinit (US5, G8) — T220–T239 -- [x] T220 [P] [US5] Failing test pinning mcp-go v1.0.0 behaviour: 404 on a non-initialize POST → `ErrSessionTerminated` and session id cleared; 404 with no session id → also `ErrSessionTerminated`; a second `Initialize` on the same client/transport stores the new session id (or document that it cannot) (`internal/upstream/core/session_reinit_mcpgo_test.go`) — FR-088 -- [x] T221 [US5] Implement `core.Client.SessionSnapshot()` and `ReinitializeSession(ctx)` without touching `connectionEpoch` (`internal/upstream/core/session_reinit.go`) — FR-080, FR-081, FR-083 -- [x] T222 [P] [US5] Failing test (SC-006): `httptest` Streamable HTTP server that forgets the session once; single call → 1 initialize, call succeeds, state stays Ready, counter = 1 (`internal/upstream/managed/session_reinit_test.go`) — FR-080, FR-084, FR-085 +- [ ] T220 [P] [US5] Failing test pinning mcp-go v1.0.0 behaviour: 404 on a non-initialize POST → `ErrSessionTerminated` and session id cleared; 404 with no session id → also `ErrSessionTerminated`; a second `Initialize` on the same client/transport stores the new session id (or document that it cannot) (`internal/upstream/core/session_reinit_mcpgo_test.go`) — FR-088 +- [ ] T221 [US5] Implement `core.Client.SessionSnapshot()` and `ReinitializeSession(ctx)` without touching `connectionEpoch` (`internal/upstream/core/session_reinit.go`) — FR-080, FR-081, FR-083 +- [ ] T222 [P] [US5] Failing test (SC-006): `httptest` Streamable HTTP server that forgets the session once; single call → 1 initialize, call succeeds, state stays Ready, counter = 1 (`internal/upstream/managed/session_reinit_test.go`) — FR-080, FR-084, FR-085 - [ ] T223 [P] [US5] Failing test: 10 concurrent calls on the same terminated session → exactly 1 initialize, 10 retries, all succeed; callers seeing a newer session id retry without re-init (`session_reinit_test.go`) — FR-082 -- [x] T231 [P] [US5] Failing test: write/destructive tool after 404 → re-init, no repeat, `session_terminated` error, next call succeeds; changed tool hash after re-init → no retry, differential update runs; health `Ping` 404 first → following call joins the re-init (no request sent without a session id); cached-tool-count `ListTools` 404 → re-init, no `Error` state (`internal/upstream/managed/session_reinit_test.go`) — FR-080–FR-083 -- [x] T232 [P] [US5] Failing test: a pinned call waiting on the re-init gate is refused with `ErrConnectionGenerationChanged` when the re-list shows its tool changed; after a re-init the upstream's `notifications/tools/list_changed` on the GET stream is still received (or, if the listener cannot be restarted, the full reconnect path runs and no retry happens) (`internal/upstream/managed/session_reinit_test.go`) — FR-083a +- [ ] T231 [P] [US5] Failing test: write/destructive tool after 404 → re-init, no repeat, `session_terminated` error, next call succeeds; changed tool hash after re-init → no retry, differential update runs; health `Ping` 404 first → following call joins the re-init (no request sent without a session id); cached-tool-count `ListTools` 404 → re-init, no `Error` state (`internal/upstream/managed/session_reinit_test.go`) — FR-080–FR-083 +- [ ] T232 [P] [US5] Failing test: a pinned call waiting on the re-init gate is refused with `ErrConnectionGenerationChanged` when the re-list shows its tool changed; after a re-init the upstream's `notifications/tools/list_changed` on the GET stream is still received (or, if the listener cannot be restarted, the full reconnect path runs and no retry happens) (`internal/upstream/managed/session_reinit_test.go`) — FR-083a - [ ] T224 [P] [US5] Failing test: retry also 404 → call fails and existing error path runs; re-initialize fails → original path; modern protocol or empty pre-call session id → no retry; non-404 errors → no retry (`session_reinit_test.go`) — FR-080, FR-084, FR-086 -- [x] T225 [US5] Implement single-flight re-init + retry-once in `managed.Client` call, `ListTools` leader and prompt paths; only the final error reaches `isConnectionError`; schedule async tool refresh after re-init (`internal/upstream/managed/client.go`, `prompts.go`) — FR-080–FR-084 +- [ ] T225 [US5] Implement single-flight re-init + retry-once in `managed.Client` call, `ListTools` leader and prompt paths; only the final error reaches `isConnectionError`; schedule async tool refresh after re-init (`internal/upstream/managed/client.go`, `prompts.go`) — FR-080–FR-084 - [ ] T226 [US5] Info log + per-client counter in diagnostics JSON (Prometheus counter if a seam exists) — FR-085 - [ ] T227 [P] [US5] Test: `CallToolOnEpoch` pinned call succeeds after re-init (epoch unchanged) — FR-083 - [ ] T228 Docs: troubleshooting note on session loss behaviour @@ -114,10 +114,10 @@ Format: `[ID] [P?] [Story] Description (files) — FR`. `[P]` = can run in paral ## Slice 113-f — mcp-cache-hints (US6, G9) — T240–T249 -- [x] T240 [P] [US6] Failing test: modern (2026-07-28) `tools/list` and `prompts/list` on `/mcp`, `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/` carry `ttlMs:0`, `cacheScope:"private"`; legacy responses carry neither (`internal/server/cache_hints_test.go`) — FR-090, FR-092, SC-007 -- [x] T241 [US6] Add `mcpserver.WithCacheHints(0, mcp.CacheScopePrivate)` to the four `NewMCPServer` calls (`internal/server/mcp.go`, `mcp_routing.go`) — FR-090, FR-091 +- [ ] T240 [P] [US6] Failing test: modern (2026-07-28) `tools/list` and `prompts/list` on `/mcp`, `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/` carry `ttlMs:0`, `cacheScope:"private"`; legacy responses carry neither (`internal/server/cache_hints_test.go`) — FR-090, FR-092, SC-007 +- [ ] T241 [US6] Add `mcpserver.WithCacheHints(0, mcp.CacheScopePrivate)` to the four `NewMCPServer` calls (`internal/server/mcp.go`, `mcp_routing.go`) — FR-090, FR-091 - [ ] T242 [US6] Re-run the three frozen tool-surface golden tests; confirm unchanged — FR-094 -- [x] T243 [US6] Tick T063/T064 in `specs/058-mcp-2026-upgrade/tasks.md` — FR-093 +- [ ] T243 [US6] Tick T063/T064 in `specs/058-mcp-2026-upgrade/tasks.md` — FR-093 - [ ] T244 Gates (as T117) - [ ] T245 Cross-model review (opencode harness, gpt-6.1-sol), ≤10 rounds - T246–T249 reserved diff --git a/specs/116-config-commit-consistency/tasks.md b/specs/116-config-commit-consistency/tasks.md index d8229165a..bb5e4c86f 100644 --- a/specs/116-config-commit-consistency/tasks.md +++ b/specs/116-config-commit-consistency/tasks.md @@ -25,7 +25,7 @@ Branch `116-pr1-config-commit` from `main`. ### Setup - [ ] T001 [US1] Add test seams (nil in production): `commitHooks`, `reconcileEntry` (at the `LoadConfiguredServers` entry on `main`), `beforeCommit`, `beforeApprovalLock`, `discoveryBeforeIndex`, `restPatchAfterParse`, `createAfterConfigRead` (`config_cow.go:93`) -- [x] T002 [P] [US1] Add `scripts/check-upstream-write-sites.sh` (allowlist: `internal/storage/**`, `internal/runtime/commit*.go`, `*_test.go`) and wire it into `.github/workflows/unit-tests.yml`. It is expected to FAIL until T030 +- [ ] T002 [P] [US1] Add `scripts/check-upstream-write-sites.sh` (allowlist: `internal/storage/**`, `internal/runtime/commit*.go`, `*_test.go`) and wire it into `.github/workflows/unit-tests.yml`. It is expected to FAIL until T030 ### Tests first (must fail on `main`) @@ -36,8 +36,8 @@ Branch `116-pr1-config-commit` from `main`. - [ ] T014 [P] [US1] `internal/server/create_commit_race_test.go`: T1.5 (parked add vs ApplyConfig profiles edit) - [ ] T015 [P] [US1] `internal/server/mcp_quarantine_index_test.go`: T1.6 (B1: MCP `quarantine_server` purges the index before returning) - [ ] T016 [P] [US1] `internal/server/shared_authbroker_patch_test.go`: T1.7 (REST and MCP patch keep `Shared` and `AuthBroker`) -- [x] T017 [P] [US1] `internal/runtime/configsvc/generations_test.go`: generation rule table (data-model §2), incarnation kept on update and reset on recreate, `SeedVersion` monotonic (T1.9) -- [x] T018 [P] [US1] `internal/storage/server_commit_test.go`: `ApplyServerCommit` is all-or-nothing (inject an error on the 2nd row → no row changed), writes the meta generation, stamps Generation/Incarnation +- [ ] T017 [P] [US1] `internal/runtime/configsvc/generations_test.go`: generation rule table (data-model §2), incarnation kept on update and reset on recreate, `SeedVersion` monotonic (T1.9) +- [ ] T018 [P] [US1] `internal/storage/server_commit_test.go`: `ApplyServerCommit` is all-or-nothing (inject an error on the 2nd row → no row changed), writes the meta generation, stamps Generation/Incarnation - [ ] T018a [P] [US1] `internal/runtime/commit_bootstrap_test.go`: T1.10 (boot with an empty storage and manager repairs the projection and schedules every enabled server; an unchanged `SaveConfiguration` still writes the file; restart keeps generations of unchanged rows) - [ ] T018b [P] [US1] `internal/runtime/commit_removal_exclusion_test.go`: T1.11 (formerly T2.3; regression coverage that a parked removal blocks a B toggle, REST update and MCP patch, which then get 404) - [ ] T018c [P] [US1] `internal/runtime/discovery_purge_race_test.go`: T1.12 (a pass parked after its approval check vs `QuarantineServer(true)` → no re-index) @@ -52,11 +52,11 @@ Branch `116-pr1-config-commit` from `main`. ### Implementation -- [x] T020 [US1] `internal/config/server_entry_equal.go`: `ServerEntryEqual` (ignores Created/Updated; includes the explicit bit, Shared, AuthBroker) with a table test +- [ ] T020 [US1] `internal/config/server_entry_equal.go`: `ServerEntryEqual` (ignores Created/Updated; includes the explicit bit, Shared, AuthBroker) with a table test - [ ] T020a [US1] `internal/commitview` leaf package: `ServerGen{Gen, Incarnation}` (PR2 adds `OAuthEpoch`, `CredentialBinding`, `Binding()`), `ErrStaleGeneration`; `TestCommitviewIsLeaf` (`go list -deps`, no module-internal import). `configsvc.ServerGen` and `upstream.ErrStaleGeneration` are aliases (review R7.2) - [ ] T021 [US1] `configsvc`: remove `SetPrePublishHook` (admission moves to commit step 2, R1.7); `ServerGen` (alias of `commitview.ServerGen`), `Snapshot.ServerGenerations`, `Prepare(PrepareInput{Config, Source, Replaced})`/`Publish`/`SeedVersion`; the replaced-name row of the generation table checked first, and `Changes` computed in `Prepare` (review R8.2). Re-express `Update`/`UpdateIfCurrent` on top. Remove `ReloadFromFile`'s raw publish (makes T017 pass) - [ ] T022 [US1] storage: `UpstreamRecord.Generation/Incarnation`, `ApplyServerCommit` (one tx; `Saves []ServerSave{Config, Stamp}` written with each row's prepared stamp verbatim, zero or above-`G` stamps rejected, review R9.3; saves through the quarantine-keeping invariant; deletes as today: row + call history; `Replaces` deleted before `Saves`, any other delete/save overlap an invariant error, review R8.2), meta key (makes T018 pass) -- [x] T023 [US1] `internal/runtime/commit.go`: `Commit`, `CommitTx` ops (with the `replaced` bookkeeping and the `Replaced` change kind, makes T018f pass; review R8.2), pipeline steps 1-6 and 8 plus after-unlock (plan §Commit pipeline). Approval locks taken in sorted order in step 4 for every name step 6 writes (changed names, hook names, removes, replacements, OAuth clears and projection-repair saves; every configured server on a global approval-policy change; plan.md step 4, PR1 review rounds 4-5), with `UnderApprovalLock` hooks. Compensating disk restore on a storage failure: capture the raw file state `{exists, bytes, mode}` inside L0 before step 5 and restore **that** (same bytes and mode, or remove the file when it was absent), never a config rebuilt from memory, with the self-write marker bookkeeping (forget the failed write's marker, record one for the restored bytes) and `desiredCfg` untouched (makes T018e and T018g pass; reviews R5.5, R9.2). The batch's per-save stamps are copied from `PreparedSnapshot.ServerGenerations` and asserted equal before `ApplyServerCommit` (makes T018i pass; review R9.3). Re-entry guard +- [ ] T023 [US1] `internal/runtime/commit.go`: `Commit`, `CommitTx` ops (with the `replaced` bookkeeping and the `Replaced` change kind, makes T018f pass; review R8.2), pipeline steps 1-6 and 8 plus after-unlock (plan §Commit pipeline). Approval locks taken in sorted order in step 4 for every name step 6 writes (changed names, hook names, removes, replacements, OAuth clears and projection-repair saves; every configured server on a global approval-policy change; plan.md step 4, PR1 review rounds 4-5), with `UnderApprovalLock` hooks. Compensating disk restore on a storage failure: capture the raw file state `{exists, bytes, mode}` inside L0 before step 5 and restore **that** (same bytes and mode, or remove the file when it was absent), never a config rebuilt from memory, with the self-write marker bookkeeping (forget the failed write's marker, record one for the restored bytes) and `desiredCfg` untouched (makes T018e and T018g pass; reviews R5.5, R9.2). The batch's per-save stamps are copied from `PreparedSnapshot.ServerGenerations` and asserted equal before `ApplyServerCommit` (makes T018i pass; review R9.3). Re-entry guard - [ ] T024 [US1] `internal/runtime/commit_reconcile.go`: move `LoadConfiguredServers`' storage phase into step 6 (diff against the stored view; OAuth-config-change clear; newly-quarantined index purge, FR-008; orphan GC on the working copy, with the empty guard at boot only). Replace the boot call (`lifecycle.go:206`) with `Commit("boot", ReconcileLive + Bootstrap)`; `Bootstrap()` anywhere else is an invariant error, and every other reconcile is `ReconcileLive()` alone (makes T018j pass; review R9.6). `LoadConfiguredServers` is deleted once T026/T027 have converted its other callers. Delete the removal goroutines (removal is synchronous in step 6) - [ ] T024a [US1] D15: move a discovery pass's final eligibility/generation check and all its index, StateView and last-good writes into one hold of L1 (coordinate with Spec 117 PR-3 G8; skip if already landed) (makes T018c pass). `ReconcileLive()`; delete `LoadConfiguredServers(cfg)`'s captured-argument form (D14) - [ ] T024b [US1] `checkToolApprovalsHeld` / `deleteToolApprovalHeld` caller-held variants and the inventory of helpers inside the D15 hold; `resolveToolQuarantineGateHeld` reads the row + `meta.quarantine_enabled` (written by the commit tx) (D16) (makes T018d pass) @@ -65,12 +65,12 @@ Branch `116-pr1-config-commit` from `main`. - [ ] T026 [US1] `ApplyConfig`/`applyConfigLocked`, `ReloadConfiguration`, `UpdateConfig`, `UpdateListenAddress`, `SaveConfiguration` (persist the live config, no storage read), `gateInitialConfig`, `SetServerShared` → `Commit` (makes T011 pass) - [ ] T027 [US1] `EnableServer`, `BulkEnableServers`, `QuarantineServer` (index purge in the commit; baseline approval after the commit, which keeps the `CommitResult` and passes its incarnation on rather than recapturing by name; PR2 T053 adds the check, review R9.5), `RestartServer`'s disk refresh → `Commit` (makes T013 pass) - [ ] T028 [US1] `internal/server`: `createServer` → `Commit(CreateServer)` and delete `createMu` (the mutex only: the #1570 create-only behaviour and test assertions stay, plan.md `createMu` note); `removeServerStorage` → `Commit(RemoveServer)` (PR1 deletes as today); `UpdateServer` → `Commit(UpdateServer)` with the in-place mutation removed; registry source add/edit/remove → `Commit(MutateGlobal)` (makes T014 and T016 pass) -- [x] T029 [US1] `internal/server/mcp.go`: update/patch merge inside `UpdateServer`; the result's connection status comes from the generation's worker result (bounded wait, as today): the update returns the server's committed generation and the monitor skips any registered instance stamped below it, so the replaced instance's ready/error state is never reported (PR1 review round 6); quarantine → `Commit(SetQuarantined)`; remove → `Commit(RemoveServer)` (makes T015 and the MCP half of T012 pass) +- [ ] T029 [US1] `internal/server/mcp.go`: update/patch merge inside `UpdateServer`; the result's connection status comes from the generation's worker result (bounded wait, as today): the update returns the server's committed generation and the monitor skips any registered instance stamped below it, so the replaced instance's ready/error state is never reported (PR1 review round 6); quarantine → `Commit(SetQuarantined)`; remove → `Commit(RemoveServer)` (makes T015 and the MCP half of T012 pass) - [ ] T029a [US1] If Spec 117 PR-2 has merged: convert `CommitServerApproval`/`FinishServerApproval` to `Commit(ExpectIncarnation(PR2: generation until then), SetQuarantined(false), UnderApprovalLock(...))` with its tests unchanged. Otherwise: add `UnderApprovalLock` with a unit test (hook runs under the lock; a hook error aborts with nothing written) -- [x] T030 [US1] `internal/httpapi/server.go` PATCH: move omitted-field, map-merge, isolation and forward-header resolution into a `func(cur *config.ServerConfig) error` passed down to `UpdateServer` (makes T012 pass; T002 now passes) +- [ ] T030 [US1] `internal/httpapi/server.go` PATCH: move omitted-field, map-merge, isolation and forward-header resolution into a `func(cur *config.ServerConfig) error` passed down to `UpdateServer` (makes T012 pass; T002 now passes) - [ ] T031 [US1] `TestCommit_*` + `TestLockOrder_*` at `-race -count=20` with `GOMAXPROCS=1` and `4`; the CI skip lane under `-tags server`; both lint passes; `./scripts/test-api-e2e.sh` - [ ] T032 [US1] Live L1 on the qa070 harness ([quickstart.md](quickstart.md)); evidence in `evidence/s116-pr1/EVIDENCE.md` -- [x] T033 [US1] Docs: `docs/architecture.md` "Config commit" section (pipeline + lock order); CLAUDE.md Recent Changes line +- [ ] T033 [US1] Docs: `docs/architecture.md` "Config commit" section (pipeline + lock order); CLAUDE.md Recent Changes line - [ ] T034 [US1] opencode Sol review in chunks (commit/storage; writers; httpapi/mcp). Fix in-scope findings only **Checkpoint**: every server writer goes through `Commit`, and storage no diff --git a/specs/123-oauth-token-encryption/tasks.md b/specs/123-oauth-token-encryption/tasks.md index 983d3ae23..772ca6516 100644 --- a/specs/123-oauth-token-encryption/tasks.md +++ b/specs/123-oauth-token-encryption/tasks.md @@ -14,9 +14,9 @@ ## Phase 0: docs correction with today's facts (FR-040, FR-041) -- [x] T090 [P] [US5] `docs/features/oauth-authentication.md`: fix lines 83, 216-224, 402 per plan "Docs plan / PR-1" (tokens are readable JSON in `config.db`, protected by file permissions; remove the keyring table) -- [x] T091 [P] [US5] `docs/docker-isolation.md:515`, `docs/features/docker-isolation.md:435`, `docs/features/sandbox-isolation.md:94,109`: state plainly that `config.db` holds the tokens in readable form; `specs/023-oauth-state-persistence/plan.md:31` annotation; the `bbolt.go` comment -- [x] T092 [US5] Grep gate: `grep -rniE 'keyring' docs/features/oauth-authentication.md` returns no storage claim; probe the published URLs after merge +- [ ] T090 [P] [US5] `docs/features/oauth-authentication.md`: fix lines 83, 216-224, 402 per plan "Docs plan / PR-1" (tokens are readable JSON in `config.db`, protected by file permissions; remove the keyring table) +- [ ] T091 [P] [US5] `docs/docker-isolation.md:515`, `docs/features/docker-isolation.md:435`, `docs/features/sandbox-isolation.md:94,109`: state plainly that `config.db` holds the tokens in readable form; `specs/023-oauth-state-persistence/plan.md:31` annotation; the `bbolt.go` comment +- [ ] T092 [US5] Grep gate: `grep -rniE 'keyring' docs/features/oauth-authentication.md` returns no storage claim; probe the published URLs after merge ## PR-2 @@ -24,33 +24,33 @@ ### Tests first -- [x] T001 [P] [US1] `internal/tokenseal/tokenseal_test.go`: round trip; 1 000 seals of the same plaintext give 1 000 distinct nonces and ciphertexts; envelope matches `^enc:v1:[0-9a-f]{16}:[A-Za-z0-9+/=]+$`; `Classify` table (`{…}` → plaintext, `enc:v1:` → sealed + kid, `enc:v2:` → unsupported, empty / other → malformed); `Seal` rejects plaintext over 1 MiB and a bucket name or bucket key containing a NUL byte (`Open` likewise) +- [ ] T001 [P] [US1] `internal/tokenseal/tokenseal_test.go`: round trip; 1 000 seals of the same plaintext give 1 000 distinct nonces and ciphertexts; envelope matches `^enc:v1:[0-9a-f]{16}:[A-Za-z0-9+/=]+$`; `Classify` table (`{…}` → plaintext, `enc:v1:` → sealed + kid, `enc:v2:` → unsupported, empty / other → malformed); `Seal` rejects plaintext over 1 MiB and a bucket name or bucket key containing a NUL byte (`Open` likewise) - [ ] T002 [P] [US2] `internal/tokenseal/open_errors_test.go`: `Open` with nil key → `no_key`; other key → `key_mismatch` with both kids; prefix kid edited to any value other than the configured kid → `key_mismatch` (no decrypt attempted); prefix kid edited to the configured kid, other bucket key, or other bucket name → `auth_failed`; damaged header or empty payload → `malformed` under every key state; precedence header → key state → payload, so characters outside the base64 alphabet or a `=` anywhere other than as the last one or two payload characters → `malformed` only with the matching key and `no_key` / `key_mismatch` under no key / another key; with the matching key, a payload of base64-alphabet characters with at most two trailing `=` that does not decode (wrong length for its padding) or is shorter than nonce + tag (truncation), and any GCM failure → `auth_failed`; explicit cases `AAAA=` → `auth_failed`, `AA=A` → `malformed`; `enc:v2:` → `unsupported_version` -- [x] T003 [P] [US3] `internal/tokenseal/key_test.go`: `ParseKey` table (32 bytes std base64 with and without padding, surrounding whitespace and one trailing newline accepted; 31/33 bytes, URL alphabet with `-`/`_`, empty, non-base64 rejected with a fixed message containing no input); HKDF known-answer vectors for the record key and kid; `fmt.Sprintf("%v|%+v|%#v", k)` and `json.Marshal(k)` contain neither the raw key nor its base64 (`String`/`GoString` print the key id only) -- [x] T004 [P] [US1] `internal/tokenseal/leaf_test.go`: `go list -deps` shows only standard-library packages (pattern of `TestCommitviewIsLeaf`) +- [ ] T003 [P] [US3] `internal/tokenseal/key_test.go`: `ParseKey` table (32 bytes std base64 with and without padding, surrounding whitespace and one trailing newline accepted; 31/33 bytes, URL alphabet with `-`/`_`, empty, non-base64 rejected with a fixed message containing no input); HKDF known-answer vectors for the record key and kid; `fmt.Sprintf("%v|%+v|%#v", k)` and `json.Marshal(k)` contain neither the raw key nor its base64 (`String`/`GoString` print the key id only) +- [ ] T004 [P] [US1] `internal/tokenseal/leaf_test.go`: `go list -deps` shows only standard-library packages (pattern of `TestCommitviewIsLeaf`) ### Implementation -- [x] T005 [US1] `internal/tokenseal/tokenseal.go`: `Key`, `ParseKey`, `ID`, `Seal`, `Open`, `Classify`, `Shape`, `Reason`, `OpenError` per plan D1-D3, D5 (makes T001-T004 pass) +- [ ] T005 [US1] `internal/tokenseal/tokenseal.go`: `Key`, `ParseKey`, `ID`, `Seal`, `Open`, `Classify`, `Shape`, `Reason`, `OpenError` per plan D1-D3, D5 (makes T001-T004 pass) ## Phase 2: storage codec seam and fail-closed writers (FR-010..016) ### Tests first -- [x] T010 [P] [US1] `internal/storage/oauth_seal_test.go`: with `WithOAuthTokenKey(k)`, every write method (`SaveOAuthToken`, `UpdateOAuthTokenIfBound`, `SaveOAuthClientIfBound` all modes, `UpdateOAuthToken`, `UpdateOAuthClientCredentials`, `SaveOAuthClientCredentialsIf*`, `ClearOAuthClient*`) leaves an `enc:v1` value whose kid is `k.ID()`; every read method returns the same record it would for a plaintext row; revision increases per write as today; a write over a plaintext row sets `meta/oauth_seal_compact_advised` in the same transaction, a write over a sealed row does not -- [x] T011 [P] [US1] `internal/storage/oauth_plaintext_golden_test.go`: without a key, the bytes written for a token save, a DCR save and a refresh-style update equal `json.Marshal` of the record (SC-003) -- [x] T012 [P] [US2] `internal/storage/oauth_undecryptable_test.go`: one table over every mutator listed in FR-013 (including the unconditional ones with no production caller) against an undecryptable row (no key / other key / swapped envelope): returns `ErrOAuthTokenUndecryptable` with the right reason and the raw bytes are unchanged (exception, FR-013: with no key, `SaveOAuthToken` overwrites a corrupt non-`enc:` value as before the feature, while any `enc:` row is always refused, and with a key every undecodable row is refused); key-only deletes (`DeleteOAuthToken`, `ClearOAuthTokenForStandaloneLogout`, `ClearOAuthState`, the Spec 116 purge (`purgeServerTx`, driven through `purgetest`), commit `OAuthClears`) still remove the row; reads return the typed error, not "not found" -- [x] T013 [P] [US2] `internal/storage/oauth_list_tolerant_test.go`: one undecryptable row and one plaintext row with invalid JSON among three good rows → `ListOAuthTokens` returns the three; `ListOAuthTokenRows` puts every row in exactly one class (`plaintext | sealed | undecryptable`) with `key_mismatch` as a reason only; `CleanupOrphanedOAuthTokens` deletes a decodable orphan, keeps both bad rows (also when their key prefix names no configured server) and reports them -- [x] T014 [P] [US1] `internal/storage/oauth_sweep_test.go`: seed several hundred ~1 KiB plaintext rows (spanning many leaf pages) plus sealed and undecryptable rows; a plaintext row with invalid JSON and one over the 1 MiB `Seal` bound are skipped with a warning (observed logger: bucket key and reason `malformed` / `too_large`, never the value) and left unchanged while the other plaintext rows are sealed; `SealPlaintextOAuthTokens` leaves zero valid plaintext rows, touches no sealed or undecryptable row, and sets the marker only when it sealed ≥1 row; with `putOAuthRecordHook` failing on the second write the whole transaction rolls back (first row still plaintext); no-op without a key -- [x] T015 [P] [US1] `internal/storage/oauth_codec_source_test.go`: `TestOAuthBucketValuesOnlyThroughCodec` per plan D6 (stdlib `go/parser` + `go/types`, receiver type `OAuthTokenRecord`; bucket access on `OAuthTokenBucket` only in the named exemptions; `UpstreamRecord`/`OAuthCompletionEvent` calls in `oauth_binding.go` not flagged) and `TestStorageOpenSitesPassOAuthKey` (every non-test `storage.NewManager(`/`storage.NewBoltDB(` call in the module passes `WithOAuthTokenKey`; the delete-only standalone `auth logout` open passes an explicit nil, named as the one exemption); both fail on `main` -- [x] T016 [US1] `internal/storage/oauth_raw_file_test.go`: `TestOAuthTokensNotInRawFile` per plan test plan (markers for access token, refresh token, client secret; sweep → close → `bbolt.Compact` → markers absent from the compacted file; a login-style write with the key set never appears in the live file; control run without a key finds every marker) +- [ ] T010 [P] [US1] `internal/storage/oauth_seal_test.go`: with `WithOAuthTokenKey(k)`, every write method (`SaveOAuthToken`, `UpdateOAuthTokenIfBound`, `SaveOAuthClientIfBound` all modes, `UpdateOAuthToken`, `UpdateOAuthClientCredentials`, `SaveOAuthClientCredentialsIf*`, `ClearOAuthClient*`) leaves an `enc:v1` value whose kid is `k.ID()`; every read method returns the same record it would for a plaintext row; revision increases per write as today; a write over a plaintext row sets `meta/oauth_seal_compact_advised` in the same transaction, a write over a sealed row does not +- [ ] T011 [P] [US1] `internal/storage/oauth_plaintext_golden_test.go`: without a key, the bytes written for a token save, a DCR save and a refresh-style update equal `json.Marshal` of the record (SC-003) +- [ ] T012 [P] [US2] `internal/storage/oauth_undecryptable_test.go`: one table over every mutator listed in FR-013 (including the unconditional ones with no production caller) against an undecryptable row (no key / other key / swapped envelope): returns `ErrOAuthTokenUndecryptable` with the right reason and the raw bytes are unchanged (exception, FR-013: with no key, `SaveOAuthToken` overwrites a corrupt non-`enc:` value as before the feature, while any `enc:` row is always refused, and with a key every undecodable row is refused); key-only deletes (`DeleteOAuthToken`, `ClearOAuthTokenForStandaloneLogout`, `ClearOAuthState`, the Spec 116 purge (`purgeServerTx`, driven through `purgetest`), commit `OAuthClears`) still remove the row; reads return the typed error, not "not found" +- [ ] T013 [P] [US2] `internal/storage/oauth_list_tolerant_test.go`: one undecryptable row and one plaintext row with invalid JSON among three good rows → `ListOAuthTokens` returns the three; `ListOAuthTokenRows` puts every row in exactly one class (`plaintext | sealed | undecryptable`) with `key_mismatch` as a reason only; `CleanupOrphanedOAuthTokens` deletes a decodable orphan, keeps both bad rows (also when their key prefix names no configured server) and reports them +- [ ] T014 [P] [US1] `internal/storage/oauth_sweep_test.go`: seed several hundred ~1 KiB plaintext rows (spanning many leaf pages) plus sealed and undecryptable rows; a plaintext row with invalid JSON and one over the 1 MiB `Seal` bound are skipped with a warning (observed logger: bucket key and reason `malformed` / `too_large`, never the value) and left unchanged while the other plaintext rows are sealed; `SealPlaintextOAuthTokens` leaves zero valid plaintext rows, touches no sealed or undecryptable row, and sets the marker only when it sealed ≥1 row; with `putOAuthRecordHook` failing on the second write the whole transaction rolls back (first row still plaintext); no-op without a key +- [ ] T015 [P] [US1] `internal/storage/oauth_codec_source_test.go`: `TestOAuthBucketValuesOnlyThroughCodec` per plan D6 (stdlib `go/parser` + `go/types`, receiver type `OAuthTokenRecord`; bucket access on `OAuthTokenBucket` only in the named exemptions; `UpstreamRecord`/`OAuthCompletionEvent` calls in `oauth_binding.go` not flagged) and `TestStorageOpenSitesPassOAuthKey` (every non-test `storage.NewManager(`/`storage.NewBoltDB(` call in the module passes `WithOAuthTokenKey`; the delete-only standalone `auth logout` open passes an explicit nil, named as the one exemption); both fail on `main` +- [ ] T016 [US1] `internal/storage/oauth_raw_file_test.go`: `TestOAuthTokensNotInRawFile` per plan test plan (markers for access token, refresh token, client secret; sweep → close → `bbolt.Compact` → markers absent from the compacted file; a login-style write with the key set never appears in the live file; control run without a key finds every marker) ### Implementation -- [x] T020 [US1] `internal/storage/options.go`: `Option`, `WithOAuthTokenKey`; variadic `opts` on `NewBoltDB` and `NewManager`; `BoltDB.oauthKey` -- [x] T021 [US1] `internal/storage/oauth_binding.go`: `encodeOAuthRecord`, `decodeOAuthRecord`, `ErrOAuthTokenUndecryptable`; `putOAuthRecord(bucket, k, key, rec)` with the explicit key parameter, the plaintext→envelope marker write and `putOAuthRecordHook`; `getOAuthRecordTx` takes the key (makes T010, T011 pass) -- [x] T022 [US2] `internal/storage/bbolt.go`: route the eight raw decode sites (plan D6) through `decodeOAuthRecord`; `SaveOAuthToken` reads first and refuses an undecryptable row; tolerant `ListOAuthTokens`; new `ListOAuthTokenRows`, `OAuthTokenRow` (makes T012, T013 pass) -- [x] T023 [US2] `internal/storage/manager.go`: `CleanupOrphanedOAuthTokens` keeps and reports undecryptable rows; `Manager` wrappers for `ListOAuthTokenRows` and the sweep; `SealPlaintextOAuthTokens` (collect, then write) + marker key constant in `models.go` (makes T013, T014 pass) +- [ ] T020 [US1] `internal/storage/options.go`: `Option`, `WithOAuthTokenKey`; variadic `opts` on `NewBoltDB` and `NewManager`; `BoltDB.oauthKey` +- [ ] T021 [US1] `internal/storage/oauth_binding.go`: `encodeOAuthRecord`, `decodeOAuthRecord`, `ErrOAuthTokenUndecryptable`; `putOAuthRecord(bucket, k, key, rec)` with the explicit key parameter, the plaintext→envelope marker write and `putOAuthRecordHook`; `getOAuthRecordTx` takes the key (makes T010, T011 pass) +- [ ] T022 [US2] `internal/storage/bbolt.go`: route the eight raw decode sites (plan D6) through `decodeOAuthRecord`; `SaveOAuthToken` reads first and refuses an undecryptable row; tolerant `ListOAuthTokens`; new `ListOAuthTokenRows`, `OAuthTokenRow` (makes T012, T013 pass) +- [ ] T023 [US2] `internal/storage/manager.go`: `CleanupOrphanedOAuthTokens` keeps and reports undecryptable rows; `Manager` wrappers for `ListOAuthTokenRows` and the sweep; `SealPlaintextOAuthTokens` (collect, then write) + marker key constant in `models.go` (makes T013, T014 pass) - [ ] T024 [US1] Pass `WithOAuthTokenKey(nil)` at every open site of plan "Open-site inventory" (Phase 3 supplies the key) so T015 passes; no behaviour change yet - [ ] T025 [US1] Make T016 pass (no code expected beyond T021-T023; if it fails, the gap is a missed write path) @@ -58,28 +58,28 @@ ### Tests first -- [x] T030 [P] [US3] `internal/config/oauth_token_key_test.go`: `ResolveOAuthTokenKey` table (empty → nil; literal; `${file:}` via a temp file; `${env:}`; `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY`; `_FILE`; env beats field; both env → `ErrOAuthTokenKeyBothSet`; unresolvable (missing file, unset env var, absent keyring entry), unusable (oversized, NUL, not a regular file, relative path), empty, malformed key → the four fixed sentences as `*StartupError` with exit 4, plus the both-set and bad-reference errors; only the unresolvable sentence is the one the standalone `auth logout` exception keys on); returned `KeySource` kind for each row and `InDataDir` true for a path under `data_dir` reached through a symlink; a grep over every returned error that it contains neither the temp path nor the key; `Config.Validate` accepts a well-formed reference to a missing file and rejects a malformed reference -- [x] T031 [P] [US3] `cmd/mcpproxy/oauth_token_key_exit_test.go`: `classifyError` maps each resolution failure to `ExitCodeConfigError` (4) through `errors.As(*config.StartupError)`, with an error message chosen so the string heuristics alone would not match -- [x] T032 [P] [US3] `internal/runtime/config_hotreload_fields_test.go` (existing canary goes red when the field is added) + `internal/runtime/oauth_token_key_restart_test.go`: editing the field is `RequiresRestart`, `pinRestartGated` keeps the running value, a save after reload writes the reference string unchanged; the key file is deleted after start and an unrelated hot-reload edit still applies +- [ ] T030 [P] [US3] `internal/config/oauth_token_key_test.go`: `ResolveOAuthTokenKey` table (empty → nil; literal; `${file:}` via a temp file; `${env:}`; `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY`; `_FILE`; env beats field; both env → `ErrOAuthTokenKeyBothSet`; unresolvable (missing file, unset env var, absent keyring entry), unusable (oversized, NUL, not a regular file, relative path), empty, malformed key → the four fixed sentences as `*StartupError` with exit 4, plus the both-set and bad-reference errors; only the unresolvable sentence is the one the standalone `auth logout` exception keys on); returned `KeySource` kind for each row and `InDataDir` true for a path under `data_dir` reached through a symlink; a grep over every returned error that it contains neither the temp path nor the key; `Config.Validate` accepts a well-formed reference to a missing file and rejects a malformed reference +- [ ] T031 [P] [US3] `cmd/mcpproxy/oauth_token_key_exit_test.go`: `classifyError` maps each resolution failure to `ExitCodeConfigError` (4) through `errors.As(*config.StartupError)`, with an error message chosen so the string heuristics alone would not match +- [ ] T032 [P] [US3] `internal/runtime/config_hotreload_fields_test.go` (existing canary goes red when the field is added) + `internal/runtime/oauth_token_key_restart_test.go`: editing the field is `RequiresRestart`, `pinRestartGated` keeps the running value, a save after reload writes the reference string unchanged; the key file is deleted after start and an unrelated hot-reload edit still applies - [ ] T033 [P] [US3] `internal/oauth` redaction test: `RedactedConfig` masks a literal key, also with `reveal_secret_headers` on; `${file:}`, `${env:}` and `${keyring:}` references come back verbatim (FR-024); a GET → `/api/v1/config/apply` round trip of the masked document leaves the stored field unchanged; a whitespace-spelled reference such as `${ file:/abs/path}`, which validation accepts, comes back as written while a non-reference is masked (one shared recogniser); no output contains the key value, key bytes or key-source contents (the public key id and key-source metadata are allowed) - [ ] T038 [P] [US3] `cmd/mcpproxy` test: with an unreadable `${file:}` key reference, `upstream list` and `doctor` (socket path) run and exit 0; `call`/`auth login` (storage-open) exit 4 and the DB bytes are unchanged; `db compact` and `db stats` run without resolving the key, also with both environment variables set; standalone `auth logout --server=` with an unresolvable source (missing key file, unset env var, absent keyring entry) still deletes the row, while both env vars set, a bad reference and an unusable (oversized, NUL, not a regular file, relative path), empty or malformed value exit 4 ### Implementation -- [x] T034 [US3] `internal/config/config.go`: field `OAuthTokenEncryptionKey`; `Validate` does the syntax-only check. `internal/config/oauth_token_key.go`: `ResolveOAuthTokenKey`, `KeySource`, env constants, `ExitCodeOAuthTokenKeyError = 4`, errors as `NewStartupError` (makes T030, T031 pass) -- [x] T035 [US3] `internal/runtime/config_hotreload.go` `restartGatedConfigFields` + `internal/runtime/restart_gated.go` `pinRestartGated` (makes T032 pass); redaction code (a field-specific rule: literal always masked, references verbatim, including `${file:}`) as T033 requires -- [x] T036 [US1] Replace the `nil` keys of T024 with the resolved key at every open site; `runtime.New` resolves once before `storage.NewManager` and keeps key + `KeySource`; shared `openStorageForCLI(cfg)` helper in `cmd/mcpproxy`; `internal/upstream/cli/client.go` returns a resolution error instead of falling back to in-memory storage, except for the delete-only standalone `auth logout` path, which opens with a nil key when the key source is missing or unreadable (file absent, env var unset, keyring entry absent); a `NewBoltDB` error after successful resolution keeps the existing fallback (makes T038 pass) -- [x] T037 [P] [US3] Confirm no Settings row on either side (`fields.ts`, `SettingsCatalog.swift`; `scripts/check-settings-parity.py` needs no change); `make swagger` (`oas/swagger.yaml`, `oas/docs.go`) +- [ ] T034 [US3] `internal/config/config.go`: field `OAuthTokenEncryptionKey`; `Validate` does the syntax-only check. `internal/config/oauth_token_key.go`: `ResolveOAuthTokenKey`, `KeySource`, env constants, `ExitCodeOAuthTokenKeyError = 4`, errors as `NewStartupError` (makes T030, T031 pass) +- [ ] T035 [US3] `internal/runtime/config_hotreload.go` `restartGatedConfigFields` + `internal/runtime/restart_gated.go` `pinRestartGated` (makes T032 pass); redaction code (a field-specific rule: literal always masked, references verbatim, including `${file:}`) as T033 requires +- [ ] T036 [US1] Replace the `nil` keys of T024 with the resolved key at every open site; `runtime.New` resolves once before `storage.NewManager` and keeps key + `KeySource`; shared `openStorageForCLI(cfg)` helper in `cmd/mcpproxy`; `internal/upstream/cli/client.go` returns a resolution error instead of falling back to in-memory storage, except for the delete-only standalone `auth logout` path, which opens with a nil key when the key source is missing or unreadable (file absent, env var unset, keyring entry absent); a `NewBoltDB` error after successful resolution keeps the existing fallback (makes T038 pass) +- [ ] T037 [P] [US3] Confirm no Settings row on either side (`fields.ts`, `SettingsCatalog.swift`; `scripts/check-settings-parity.py` needs no change); `make swagger` (`oas/swagger.yaml`, `oas/docs.go`) ## Phase 4: boot sweep, OAuth read paths and health (FR-016, FR-031) ### Tests first -- [x] T040 [P] [US1] `internal/runtime/oauth_seal_boot_test.go`: with a key and plaintext rows, after `runtime.New` every valid plaintext row is sealed, and a hook asserts the sweep ran (after the shutdown marker is armed) before the upstream manager, the refresh manager and every other OAuth consumer were constructed; a transaction-level sweep failure (fault hook) makes `runtime.New` close storage and return an error -- [x] T041 [P] [US2] `internal/oauth/persistent_token_store_undecryptable_test.go`: `GetToken` returns the typed error (not `transport.ErrNoToken`); `HasPersistedTokenBound` and `GetPersistedRefreshToken` return it through their new error results; a login (`WithLoginClient` save of token + DCR) against an undecryptable row fails and leaves the bytes; refresh manager `Start` schedules the decodable servers and skips the undecryptable one +- [ ] T040 [P] [US1] `internal/runtime/oauth_seal_boot_test.go`: with a key and plaintext rows, after `runtime.New` every valid plaintext row is sealed, and a hook asserts the sweep ran (after the shutdown marker is armed) before the upstream manager, the refresh manager and every other OAuth consumer were constructed; a transaction-level sweep failure (fault hook) makes `runtime.New` close storage and return an error +- [ ] T041 [P] [US2] `internal/oauth/persistent_token_store_undecryptable_test.go`: `GetToken` returns the typed error (not `transport.ErrNoToken`); `HasPersistedTokenBound` and `GetPersistedRefreshToken` return it through their new error results; a login (`WithLoginClient` save of token + DCR) against an undecryptable row fails and leaves the bytes; refresh manager `Start` schedules the decodable servers and skips the undecryptable one - [ ] T047 [P] [US2] `internal/upstream` tests over the plan D8 inventory: for each site, an undecryptable row produces the typed error / `OAuthTokenUndecryptable` last error and never starts an OAuth flow (`connection_oauth.go` precheck paths, `client.go:852`, `manager.go:3000`, `manager.go:3547`); plus the read-path inventory source test (fails when a new production caller of `GetOAuthToken*`/`HasPersistedToken*`/`GetPersistedRefreshToken` is not listed) -- [x] T042 [P] [US2] `internal/health/calculator_oauth_undecryptable_test.go` + runtime server-list test: an undecryptable row yields `unhealthy`, action `configure`, the reason in the detail, code `MCPX_OAUTH_TOKEN_UNDECRYPTABLE`; never `login`, also when the server is connected (anonymous connection, a later call needs authentication); a connected server that needs no login stays healthy and the static-header exclusion still applies -- [x] T043 [P] [US2] `internal/diagnostics` catalog contract test fails until the new code has a registry entry and `docs/errors/MCPX_OAUTH_TOKEN_UNDECRYPTABLE.md` +- [ ] T042 [P] [US2] `internal/health/calculator_oauth_undecryptable_test.go` + runtime server-list test: an undecryptable row yields `unhealthy`, action `configure`, the reason in the detail, code `MCPX_OAUTH_TOKEN_UNDECRYPTABLE`; never `login`, also when the server is connected (anonymous connection, a later call needs authentication); a connected server that needs no login stays healthy and the static-header exclusion still applies +- [ ] T043 [P] [US2] `internal/diagnostics` catalog contract test fails until the new code has a registry entry and `docs/errors/MCPX_OAUTH_TOKEN_UNDECRYPTABLE.md` - [ ] T056 [P] [US2] login refusal test (PR-2; the richer pre-flight UX stays in PR-3): `mcpproxy auth login --server=` and the REST login trigger and the connection path against an undecryptable row return `MCPX_OAUTH_TOKEN_UNDECRYPTABLE` and make no HTTP request to the authorization server or DCR endpoint (fixture counts requests) ### Implementation @@ -91,8 +91,8 @@ ## Phase 6a: feature documentation (FR-041, FR-042) -- [x] T061 [P] [US5] New `docs/features/oauth-token-encryption.md` per plan "Docs plan / PR-2" (including which delivery protects against disk/VM snapshots, i.e. only where the captured storage does not hold the means to recover the key: TPM-bound credential, external secret manager, key on another volume; and which only against copies of `config.db`, notably a host-key-only `LoadCredentialEncrypted=` credential, a plain `LoadCredential=` file and a same-volume Compose secret); add it to `website/sidebars.js` next to `features/oauth-authentication` (the `features/**` glob in `docusaurus.config.js` already publishes it); link it from `docs/features/oauth-authentication.md` -- [x] T062 [P] [US5] `docs/configuration/config-file.md`, `docs/configuration/environment-variables.md`, `docs/configuration.md` tables +- [ ] T061 [P] [US5] New `docs/features/oauth-token-encryption.md` per plan "Docs plan / PR-2" (including which delivery protects against disk/VM snapshots, i.e. only where the captured storage does not hold the means to recover the key: TPM-bound credential, external secret manager, key on another volume; and which only against copies of `config.db`, notably a host-key-only `LoadCredentialEncrypted=` credential, a plain `LoadCredential=` file and a same-volume Compose secret); add it to `website/sidebars.js` next to `features/oauth-authentication` (the `features/**` glob in `docusaurus.config.js` already publishes it); link it from `docs/features/oauth-authentication.md` +- [ ] T062 [P] [US5] `docs/configuration/config-file.md`, `docs/configuration/environment-variables.md`, `docs/configuration.md` tables - [ ] T063 [P] [US5] Extend the PR-1 isolation-page and OAuth-page sentences with the encryption condition and the same-user caveat ## PR-3 @@ -101,26 +101,26 @@ ### Tests first -- [x] T050 [P] [US2] `internal/management/diagnostics_oauth_storage_test.go`: section counts for a mixed bucket form a partition that sums to the row total, with `undecryptable_by_reason`; per-server reasons; warnings `literal_key`, `key_file_in_data_dir`, `plaintext_rows_with_key`, `compaction_advised`, `backup_file_present` computed from the runtime's `KeySource` and data dir; a scoped caller sees only its visible servers and no kid; no output contains key bytes or the reference path -- [x] T051 [P] [US4] `cmd/mcpproxy/auth_tokens_cmd_test.go`: `status` text and `-o json`; `encrypt` and `--dry-run`; `decrypt --yes` (and refusal without `--yes`); no key → exit 4; locked DB → exit 3; exit 1 when rows remain in the unwanted state; config reference unreadable while `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY_FILE` supplies the key → works; several hundred rows spanning many leaf pages all converted; after `decrypt`, every row decodes with plain `json.Unmarshal` (downgrade simulation) -- [x] T052 [P] [US1] `cmd/mcpproxy/db_cmd_test.go`: `db compact` with the default `--keep-backup=true` keeps the marker and prints the `config.db.bak` note; `--keep-backup=false` removes the marker; doctor shows `backup_file_present` until the `.bak` is deleted +- [ ] T050 [P] [US2] `internal/management/diagnostics_oauth_storage_test.go`: section counts for a mixed bucket form a partition that sums to the row total, with `undecryptable_by_reason`; per-server reasons; warnings `literal_key`, `key_file_in_data_dir`, `plaintext_rows_with_key`, `compaction_advised`, `backup_file_present` computed from the runtime's `KeySource` and data dir; a scoped caller sees only its visible servers and no kid; no output contains key bytes or the reference path +- [ ] T051 [P] [US4] `cmd/mcpproxy/auth_tokens_cmd_test.go`: `status` text and `-o json`; `encrypt` and `--dry-run`; `decrypt --yes` (and refusal without `--yes`); no key → exit 4; locked DB → exit 3; exit 1 when rows remain in the unwanted state; config reference unreadable while `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY_FILE` supplies the key → works; several hundred rows spanning many leaf pages all converted; after `decrypt`, every row decodes with plain `json.Unmarshal` (downgrade simulation) +- [ ] T052 [P] [US1] `cmd/mcpproxy/db_cmd_test.go`: `db compact` with the default `--keep-backup=true` keeps the marker and prints the `config.db.bak` note; `--keep-backup=false` removes the marker; doctor shows `backup_file_present` until the `.bak` is deleted ### Implementation -- [x] T053 [US2] `internal/contracts/types.go` `OAuthTokenStorageReport`; runtime accessor (key, `KeySource`, rows, marker, `.bak` presence); `internal/management/diagnostics.go` fill + `RuntimeWarnings`; doctor CLI rendering; `make swagger` (makes T050 pass) -- [x] T054 [US4] `cmd/mcpproxy/auth_tokens_cmd.go` under `auth`, through `openStorageForCLI` (makes T051 pass) -- [x] T055 [US1] `cmd/mcpproxy/db_cmd.go` marker handling and note (makes T052 pass) +- [ ] T053 [US2] `internal/contracts/types.go` `OAuthTokenStorageReport`; runtime accessor (key, `KeySource`, rows, marker, `.bak` presence); `internal/management/diagnostics.go` fill + `RuntimeWarnings`; doctor CLI rendering; `make swagger` (makes T050 pass) +- [ ] T054 [US4] `cmd/mcpproxy/auth_tokens_cmd.go` under `auth`, through `openStorageForCLI` (makes T051 pass) +- [ ] T055 [US1] `cmd/mcpproxy/db_cmd.go` marker handling and note (makes T052 pass) ## Phase 6b: surface documentation -- [x] T064 [P] [US5] `docs/features/oauth-token-encryption.md`: doctor output, downgrade / disable / rotation with the offline key form (plan "Docs plan / PR-3"; rotation = decrypt with the old key, change the key, encrypt, then `db compact --keep-backup=false`, delete any existing `config.db.bak`, warn about copies made during the plaintext interval) -- [x] T065 [P] [US5] `docs/cli/command-reference.md` (`auth tokens`, the doctor section), `docs/api/rest-api.md` (`oauth_token_storage` in `GET /api/v1/diagnostics`), `docs/cli/db-commands.md` (compaction and backup note) +- [ ] T064 [P] [US5] `docs/features/oauth-token-encryption.md`: doctor output, downgrade / disable / rotation with the offline key form (plan "Docs plan / PR-3"; rotation = decrypt with the old key, change the key, encrypt, then `db compact --keep-backup=false`, delete any existing `config.db.bak`, warn about copies made during the plaintext interval) +- [ ] T065 [P] [US5] `docs/cli/command-reference.md` (`auth tokens`, the doctor section), `docs/api/rest-api.md` (`oauth_token_storage` in `GET /api/v1/diagnostics`), `docs/cli/db-commands.md` (compaction and backup note) ## Phase 7: verification (PR-2 and PR-3) - [ ] T070 [US1] (PR-2) e2e step with the OAuth test fixture (`oauth-e2e-testing` setup): login with a key → raw scan of `config.db` → restart with the key reference removed (health detail, bytes unchanged) → restart with a missing key file (exit 4, bytes unchanged) → restart with key (authenticated, no browser) (US1, US2, US3, SC-001, SC-002) - [ ] T071 [US1] (PR-2) `BenchmarkGetOAuthToken{Plaintext,Sealed}` mean ns/op and allocs/op recorded in the PR (SC-005, informational) -- [x] T072 Gates: golangci-lint v2 bare and `--build-tags server`; `go test -race` over the packages in plan "Technical Context" and the CI `-tags server` lane; `./scripts/test-api-e2e.sh`; swagger verify; `scripts/check-settings-parity.py`; `scripts/check-upstream-write-sites.sh` +- [ ] T072 Gates: golangci-lint v2 bare and `--build-tags server`; `go test -race` over the packages in plan "Technical Context" and the CI `-tags server` lane; `./scripts/test-api-e2e.sh`; swagger verify; `scripts/check-settings-parity.py`; `scripts/check-upstream-write-sites.sh` - [ ] T073 SC-004 sweep: grep all captured test logs, errors, CLI and REST outputs for the test key bytes, its base64 and the key-file contents; the public key id and key-source metadata are allowed (also assert that `GET /api/v1/secrets/config` reports presence only for a `${env:}` / `${keyring:}` key reference and returns no value, and that daemon key resolution for use happens once; the config file itself intentionally keeps a literal key or the original `${...}` reference; assert only that a save never replaces a reference with resolved key material, that `GET /api/v1/config` masks a literal key even with `reveal_secret_headers` and shows a reference as written; an operator-written `${file:}` path is not a violation, resolved values and key-file contents are) - [ ] T074 Cross-model review rounds per the maintainer's reviewer ladder (crypto + storage change: request the hard-problem reviewer for Phases 1-2) From 4e96ed23ee9203b1e8cf18eca701d502899e6146 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 06:36:03 +0000 Subject: [PATCH 10/11] chore(specs): gardener checkbox sync --- specs/124-session-failure-timeline/tasks.md | 80 ++++++++++----------- 1 file changed, 40 insertions(+), 40 deletions(-) diff --git a/specs/124-session-failure-timeline/tasks.md b/specs/124-session-failure-timeline/tasks.md index 6439dbaae..d13f06d33 100644 --- a/specs/124-session-failure-timeline/tasks.md +++ b/specs/124-session-failure-timeline/tasks.md @@ -22,33 +22,33 @@ ### Tests first -- [ ] T010 [P] [US1] `internal/storage/attempt_role_test.go`: table for `attemptRole`: `tool_call` success, error, `blocked`, `rejected`; mirror `internal_tool_call` named `call_tool_*` (not counted); other `internal_tool_call`; blocked `policy_decision` sole (counted, block) and with `Companion` (not counted); warning `policy_decision` (not counted); any counted row with error class `proxy_policy` is a block -- [ ] T011 [US1] `internal/server/attempt_invariant_test.go`: drive every site that emits a blocking decision, a rejection or a refusal through its real handler and assert exactly one counted row per attempt, with attempt, failure and block counts separately. Sites: `mcp_routing.go:544-625` and `:744-745`, `mcp.go:3167` and `:3768-3769`, `mcp_code_execution.go:106` and `:1145` with `:1112`, replay `server.go:4533-4543`, `output_sanitisation.go:113`, strict and warn output-schema validation (`mcp.go:8809`), a limiter shed, a refused sandbox child (`mcp_code_execution.go:1293-1299`), builtin management refusals (`mcp.go:4652-4691`) -- [ ] T012 [P] [US1] `internal/runtime/concurrency_rejections_test.go`: several shed children of one REST call get distinct request ids, and a child's rejection row carries the id its completion row would have carried +- [x] T010 [P] [US1] `internal/storage/attempt_role_test.go`: table for `attemptRole`: `tool_call` success, error, `blocked`, `rejected`; mirror `internal_tool_call` named `call_tool_*` (not counted); other `internal_tool_call`; blocked `policy_decision` sole (counted, block) and with `Companion` (not counted); warning `policy_decision` (not counted); any counted row with error class `proxy_policy` is a block +- [x] T011 [US1] `internal/server/attempt_invariant_test.go`: drive every site that emits a blocking decision, a rejection or a refusal through its real handler and assert exactly one counted row per attempt, with attempt, failure and block counts separately. Sites: `mcp_routing.go:544-625` and `:744-745`, `mcp.go:3167` and `:3768-3769`, `mcp_code_execution.go:106` and `:1145` with `:1112`, replay `server.go:4533-4543`, `output_sanitisation.go:113`, strict and warn output-schema validation (`mcp.go:8809`), a limiter shed, a refused sandbox child (`mcp_code_execution.go:1293-1299`), builtin management refusals (`mcp.go:4652-4691`) +- [x] T012 [P] [US1] `internal/runtime/concurrency_rejections_test.go`: several shed children of one REST call get distinct request ids, and a child's rejection row carries the id its completion row would have carried ### Implementation -- [ ] T013 [US1] `internal/storage/activity_models.go`: add `Companion bool`, `BodiesRemoved bool`, `RunName string` to `ActivityRecord` (all `omitempty`); new `internal/storage/attempt_role.go` with `attemptRole(record)` (makes T010 pass) -- [ ] T014 [US1] `internal/server/mcp.go` (`emitActivityPolicyDecision` funnel, `:1180`), `internal/runtime/event_bus.go` (`emitActivityPolicyDecision`): add the companion argument; every call site passes it explicitly per plan D2 "Which blocking decisions have a companion" -- [ ] T015 [US1] `internal/server/mcp.go:4652-4691`: builtin management refusals note the `proxy_policy` outcome (`callerr.NoteOutcome`), as the sanitisation path does -- [ ] T016 [US1] `internal/reqcontext` (attempt id key), `internal/server/mcp.go` and `internal/server/mcp_code_execution.go:897-900` (set it where the request id is minted), `internal/runtime/concurrency_rejections.go:53-57` (read it, fall back to the transport id) (makes T011, T012 pass) +- [x] T013 [US1] `internal/storage/activity_models.go`: add `Companion bool`, `BodiesRemoved bool`, `RunName string` to `ActivityRecord` (all `omitempty`); new `internal/storage/attempt_role.go` with `attemptRole(record)` (makes T010 pass) +- [x] T014 [US1] `internal/server/mcp.go` (`emitActivityPolicyDecision` funnel, `:1180`), `internal/runtime/event_bus.go` (`emitActivityPolicyDecision`): add the companion argument; every call site passes it explicitly per plan D2 "Which blocking decisions have a companion" +- [x] T015 [US1] `internal/server/mcp.go:4652-4691`: builtin management refusals note the `proxy_policy` outcome (`callerr.NoteOutcome`), as the sanitisation path does +- [x] T016 [US1] `internal/reqcontext` (attempt id key), `internal/server/mcp.go` and `internal/server/mcp_code_execution.go:897-900` (set it where the request id is minted), `internal/runtime/concurrency_rejections.go:53-57` (read it, fall back to the transport id) (makes T011, T012 pass) ## Phase 3: work session per request (plan D1; FR-001..009, FR-019) ### Tests first -- [ ] T020 [P] [US2] `internal/runtime/worksession_test.go`, injected `now`: the principal carries the token prefix for agent tokens and for client credentials; a client credential rotated inside the idle window gets a new session; run name is its own key field after the principal and never joins two principals; `Touch(id)` moves the idle clock and reinstates a reaped entry; the 1,001st named session of a principal in one day ignores its name -- [ ] T021 [P] [US2] `internal/auth/agent_token_test.go` and `internal/storage/client_credentials_test.go`: during a staged client rotation a pending-hash match builds an auth context whose `TokenPrefix` is `PendingPrefix`; the stored record is unchanged; after finalization the prefix is the same value -- [ ] T022 [US2] `internal/server/worksession_resolution_test.go`: resolution for the four surfaces (legacy MCP connection, modern MCP request, REST with each `X-MCPProxy-Client` surface, CLI); two tokens on one legacy connection get two sessions; old and pending secret during a staged rotation get two sessions and the pending one keeps its session after finalization; `code_execution` sub-calls inherit the parent's session (FR-005); a legacy connection keeps the id it had (FR-006); no connection record is written for a modern request (Spec 058 US3) +- [x] T020 [P] [US2] `internal/runtime/worksession_test.go`, injected `now`: the principal carries the token prefix for agent tokens and for client credentials; a client credential rotated inside the idle window gets a new session; run name is its own key field after the principal and never joins two principals; `Touch(id)` moves the idle clock and reinstates a reaped entry; the 1,001st named session of a principal in one day ignores its name +- [x] T021 [P] [US2] `internal/auth/agent_token_test.go` and `internal/storage/client_credentials_test.go`: during a staged client rotation a pending-hash match builds an auth context whose `TokenPrefix` is `PendingPrefix`; the stored record is unchanged; after finalization the prefix is the same value +- [x] T022 [US2] `internal/server/worksession_resolution_test.go`: resolution for the four surfaces (legacy MCP connection, modern MCP request, REST with each `X-MCPProxy-Client` surface, CLI); two tokens on one legacy connection get two sessions; old and pending secret during a staged rotation get two sessions and the pending one keeps its session after finalization; `code_execution` sub-calls inherit the parent's session (FR-005); a legacy connection keeps the id it had (FR-006); no connection record is written for a modern request (Spec 058 US3) - [ ] T023 [P] [US2] `internal/server/run_header_test.go`: `X-MCPProxy-Run` accepted at 1 to 128 printable characters on REST and MCP over HTTP; an invalid value does not fail the call and is logged once per principal per process (FR-004); the header never reaches an upstream ### Implementation -- [ ] T024 [US2] `internal/runtime/worksession.go`: `WorkSessionIdentity` gains the run name field; `Touch`; named-session count per principal per day (makes T020 pass) -- [ ] T025 [US2] `internal/storage/agent_tokens.go:1024-1032`, `internal/auth/agent_token.go:307-314`: validation reports which hash matched; the auth context for a pending match carries `PendingPrefix`. List every reader of `AuthContext.TokenPrefix` in the PR description and check each against the new value (makes T021 pass) -- [ ] T026 [US2] `internal/server/workspace.go` (`principalFromContext` with generation), `internal/server/session_store.go` (per-principal map in `SessionInfo` replacing the single cached id), new `internal/server/worksession_resolve.go` (builds the identity from the request context on every recorded attempt) -- [ ] T027 [US2] `internal/server/mcp_activity_attribution.go`, `internal/runtime/activity_attribution.go`: `WorkSessionID`, `UserID` and `RunName` on the attribution, filled at the emit site; `internal/runtime/activity_service.go`: every row builder copies them (`:566-587`, `:716`, `:779-796`, `:1017`, `:1115`) and falls back to `resolveWorkSession(sessionID)` when the attribution is empty -- [ ] T028 [US2] `internal/httpapi/middleware.go` and the MCP HTTP entry: read and validate `X-MCPProxy-Run` in one place, store it on the request context; confirm it is absent from the upstream forwarding allow-list; invert T001 (makes T022, T023 pass) +- [x] T024 [US2] `internal/runtime/worksession.go`: `WorkSessionIdentity` gains the run name field; `Touch`; named-session count per principal per day (makes T020 pass) +- [x] T025 [US2] `internal/storage/agent_tokens.go:1024-1032`, `internal/auth/agent_token.go:307-314`: validation reports which hash matched; the auth context for a pending match carries `PendingPrefix`. List every reader of `AuthContext.TokenPrefix` in the PR description and check each against the new value (makes T021 pass) +- [x] T026 [US2] `internal/server/workspace.go` (`principalFromContext` with generation), `internal/server/session_store.go` (per-principal map in `SessionInfo` replacing the single cached id), new `internal/server/worksession_resolve.go` (builds the identity from the request context on every recorded attempt) +- [x] T027 [US2] `internal/server/mcp_activity_attribution.go`, `internal/runtime/activity_attribution.go`: `WorkSessionID`, `UserID` and `RunName` on the attribution, filled at the emit site; `internal/runtime/activity_service.go`: every row builder copies them (`:566-587`, `:716`, `:779-796`, `:1017`, `:1115`) and falls back to `resolveWorkSession(sessionID)` when the attribution is empty +- [x] T028 [US2] `internal/httpapi/middleware.go` and the MCP HTTP entry: read and validate `X-MCPProxy-Run` in one place, store it on the request context; confirm it is absent from the upstream forwarding allow-list; invert T001 (makes T022, T023 pass) ## Phase 4: storage, summaries, backfill (plan D3, Data Model; FR-010..018, FR-049) @@ -60,10 +60,10 @@ ### Implementation -- [ ] T033 [US1] `internal/storage/work_sessions.go` (new): buckets `work_sessions`, `work_session_rows`, `upstream_events_by_server`; summary and partition types per plan Data Model; `internal/storage/activity.go` (`SaveActivity`, `:55`): index entry and summary update in the same transaction (makes T030 pass) -- [ ] T034 [US3] `internal/storage/work_session_backfill.go` (new): batches of 1,000 keys per transaction, role pairing with a five-second window carried across batches, metadata marker; started from `internal/runtime` as a goroutine joined in `Runtime.Close` (makes T031 pass) +- [x] T033 [US1] `internal/storage/work_sessions.go` (new): buckets `work_sessions`, `work_session_rows`, `upstream_events_by_server`; summary and partition types per plan Data Model; `internal/storage/activity.go` (`SaveActivity`, `:55`): index entry and summary update in the same transaction (makes T030 pass) +- [x] T034 [US3] `internal/storage/work_session_backfill.go` (new): batches of 1,000 keys per transaction, role pairing with a five-second window carried across batches, metadata marker; started from `internal/runtime` as a goroutine joined in `Runtime.Close` (makes T031 pass) - [ ] T035 [US3] `internal/storage/work_session_repair.go` (new): startup walk of distinct work-session ids in the index (one seek per session); `internal/runtime`: at start, a summary with no end gets its last activity time as its end; the cleanup pass and shutdown set `ended_at` once the idle window has closed (FR-015) (makes T032 pass) -- [ ] T036 [US3] `internal/storage/manager.go:1607`: `sessionRetentionLimit = 100` no longer applies to work-session summaries (FR-030); the connection-session store keeps its own limit +- [x] T036 [US3] `internal/storage/manager.go:1607`: `sessionRetentionLimit = 100` no longer applies to work-session summaries (FR-030); the connection-session store keeps its own limit ## Phase 5: retention and pruning (plan D4; FR-030..039, FR-070) @@ -71,15 +71,15 @@ - [ ] T040 [P] [US3] `internal/storage/activity_prune_test.go`, small caps: session window deletes summaries and index entries and keeps rows (FR-036); the age cap removes index entries, sets `truncated_start`, lowers only stored counters; size pass order 3a bodies (every non-body field kept, `BodiesRemoved` set, progress key honoured), 3b rows outside the window, 3c whole sessions oldest last-activity first, 3d trim of the last session; at most 1,000 rows per transaction; the activity bucket and the three new buckets together end at or below the byte budget - [ ] T041 [P] [US3] `internal/runtime/activity_retention_test.go`: the shortfall record holds time, cause (`age_cap`, `record_cap`, `size_cap`) and the start of the oldest complete session; it is cleared only when the last in-window removal is older than the window, not by a quiet pass -- [ ] T042 [P] [US3] `internal/config/effective_bounds_test.go`: `session_retention_days` default 7 through its `Effective*` reader; `activity_max_records` default 400,000; an explicit `100000` in the file is kept -- [ ] T043 [P] [US3] `frontend/tests/unit/settings-session-retention.spec.ts`: the field loads, edits and saves beside its siblings +- [x] T042 [P] [US3] `internal/config/effective_bounds_test.go`: `session_retention_days` default 7 through its `Effective*` reader; `activity_max_records` default 400,000; an explicit `100000` in the file is kept +- [x] T043 [P] [US3] `frontend/tests/unit/settings-session-retention.spec.ts`: the field loads, edits and saves beside its siblings ### Implementation -- [ ] T044 [US3] `internal/storage/activity.go` (`:419-528`): session-aware prune functions per plan D4 steps 1 to 3d (makes T040 pass) -- [ ] T045 [US3] `internal/runtime/activity_service.go` (`runRetentionLoop`, `:339-407`): call order, shortfall metadata record, accessor for the doctor section (makes T041 pass) -- [ ] T046 [US3] `internal/config/config.go`, `internal/config/effective_bounds.go`: the new field at all five wiring points (struct, defaults, load, save, effective reader) and the changed default (makes T042 pass) -- [ ] T047 [US3] `frontend/src/views/settings/fields.ts:585-587`: `session_retention_days`, number, minimum 1, restart required (makes T043 pass) +- [x] T044 [US3] `internal/storage/activity.go` (`:419-528`): session-aware prune functions per plan D4 steps 1 to 3d (makes T040 pass) +- [x] T045 [US3] `internal/runtime/activity_service.go` (`runRetentionLoop`, `:339-407`): call order, shortfall metadata record, accessor for the doctor section (makes T041 pass) +- [x] T046 [US3] `internal/config/config.go`, `internal/config/effective_bounds.go`: the new field at all five wiring points (struct, defaults, load, save, effective reader) and the changed default (makes T042 pass) +- [x] T047 [US3] `frontend/src/views/settings/fields.ts:585-587`: `session_retention_days`, number, minimum 1, restart required (makes T043 pass) ## Phase 6: upstream events (plan D5; FR-020..025) @@ -87,43 +87,43 @@ - [ ] T050 [US1] `internal/upstream/types/transition_capture_test.go`: every state mutation appends a record under the lock with old state, new state, time and a copy of the last error; one goroutine delivers them in mutation order; a full queue merges the oldest unsent records of one kind and always delivers the final Ready; run with `-race` - [ ] T051 [US1] `internal/runtime/upstream_event_source_test.go`: kill a stdio fixture, refuse a connection, expire an OAuth login; record the states and `MCPX_*` codes the observer receives. Correct the kind table in plan D5 from this output before T056 -- [ ] T052 [P] [US1] `internal/oauth/refresh_coordinator_test.go`: the audit observer reports once per executed failed refresh: transient reactive and proactive failures report; several waiters on one flight give one report; a cancelled caller, a latched terminal outcome, a cooldown and a retired instance (`dialgate.IsRetired`) give none -- [ ] T053 [P] [US1] `internal/oauth/refresh_manager_test.go`: one per-server notification number taken under the lock for every schedule install and every accepted failure; the token-saved and failure events carry it +- [x] T052 [P] [US1] `internal/oauth/refresh_coordinator_test.go`: the audit observer reports once per executed failed refresh: transient reactive and proactive failures report; several waiters on one flight give one report; a cancelled caller, a latched terminal outcome, a cooldown and a retired instance (`dialgate.IsRetired`) give none +- [x] T053 [P] [US1] `internal/oauth/refresh_manager_test.go`: one per-server notification number taken under the lock for every schedule install and every accepted failure; the token-saved and failure events carry it - [ ] T054 [P] [US1] `internal/runtime/upstream_event_collapser_test.go`, injected clock: repeats within one minute rewrite one row with a count and first and last times; 120 rows per server per hour, then merge into the latest row of that kind; collapse per owner, never across owners; SC-007 storm of one failure per second for 24 hours gives at most 2,880 rows; one open `login_required` per server and owner; a stale failure does not open the mark and a stale save does not clear it; a failure delivered before the save that installed its schedule leaves the mark open; a successful login clears it - [ ] T055 [P] [US5] `internal/httpapi/activity_event_owner_test.go` (`-tags server` for the two-user cases): a foreign user's credential event is absent from the activity list, summary, export and SSE frames, and its detail takes the ordinary not-found exit; counts and paging are computed after the predicate ### Implementation -- [ ] T056 [US1] `internal/upstream/types/types.go`: transition queue and drain goroutine, existing `onStateChange` untouched; `internal/upstream` manager: one observer registration point (makes T050 pass) -- [ ] T057 [US1] `internal/oauth/refresh_coordinator.go` (`flight`, after `req.Refresh`, `:385-386`, past the retired check `:420-424`): audit observer; `internal/oauth/refresh_manager.go`: notification counter, new token-saved event, number returned by `failScheduleIfCurrent` (makes T052, T053 pass) -- [ ] T058 [US1] `internal/runtime/events.go`, `internal/runtime/lifecycle.go`: register the observer at start, classify with `diagnostics.Classify`, publish the new bus event without blocking; `internal/runtime/activity_service.go`: write `upstream_event` rows with the captured time, code and `diagnostics.Get(code).UserMessage` only (FR-021), the owner user id in the server edition, the collapser, and the `upstream_events_by_server` entry (makes T051, T054 pass) -- [ ] T059 [US1] Register the type everywhere a type is listed: storage type constants, `ACTIVITY_TYPE_LABELS` in `frontend/src/utils/activity.ts`, `activitySystemTypes` in `cmd/mcpproxy/activity_cmd.go:394-401`, and whatever the backend/frontend label-parity test reads; the System view shows and filters the rows (FR-024) -- [ ] T060 [US5] `internal/storage/activity_models.go` (`ActivityFilter`): predicate "not an owned upstream event, or the caller is an administrator or its owner"; `internal/httpapi/activity.go` (`applyActivityScope` `:161-169`, detail `:303-310`, export) and the activity SSE path call it (makes T055 pass) +- [x] T056 [US1] `internal/upstream/types/types.go`: transition queue and drain goroutine, existing `onStateChange` untouched; `internal/upstream` manager: one observer registration point (makes T050 pass) +- [x] T057 [US1] `internal/oauth/refresh_coordinator.go` (`flight`, after `req.Refresh`, `:385-386`, past the retired check `:420-424`): audit observer; `internal/oauth/refresh_manager.go`: notification counter, new token-saved event, number returned by `failScheduleIfCurrent` (makes T052, T053 pass) +- [x] T058 [US1] `internal/runtime/events.go`, `internal/runtime/lifecycle.go`: register the observer at start, classify with `diagnostics.Classify`, publish the new bus event without blocking; `internal/runtime/activity_service.go`: write `upstream_event` rows with the captured time, code and `diagnostics.Get(code).UserMessage` only (FR-021), the owner user id in the server edition, the collapser, and the `upstream_events_by_server` entry (makes T051, T054 pass) +- [x] T059 [US1] Register the type everywhere a type is listed: storage type constants, `ACTIVITY_TYPE_LABELS` in `frontend/src/utils/activity.ts`, `activitySystemTypes` in `cmd/mcpproxy/activity_cmd.go:394-401`, and whatever the backend/frontend label-parity test reads; the System view shows and filters the rows (FR-024) +- [x] T060 [US5] `internal/storage/activity_models.go` (`ActivityFilter`): predicate "not an owned upstream event, or the caller is an administrator or its owner"; `internal/httpapi/activity.go` (`applyActivityScope` `:161-169`, detail `:303-310`, export) and the activity SSE path call it (makes T055 pass) ## Phase 7: read doors (plan D6; FR-040..049) ### Tests first - [ ] T070 [P] [US5] `internal/httpapi/work_sessions_authz_test.go`: authorization table for the three doors with admin, two agent tokens, a pinned token and, under `-tags server`, two users; a foreign id and a missing id give the same not found; activity on a hidden server changes nothing a scoped caller reads (start, end, status, counts, failure facts, sort order); connection count, profile and the truncated-start marker are omitted for a scoped caller; a scoped token sees a shared upstream event of a server in reach -- [ ] T071 [P] [US1] `internal/httpapi/work_sessions_test.go`: list filters `failed`, `include_blocked`, `token`, `client`, `profile`, `run`, `error_class`, `since`, `until`, sort by `last_failure` and `last_activity`, `limit` at most 100; timeline `at=first_failure|failure:|row:|end` with `before` and `after` at most 250 and default 20; current failure index and total over stored failures in reach; with pruned failures the response gives the lifetime count and says earlier failures are no longer stored; bodies omitted unless `include_bodies`; upstream events merged in time order inside the span (SC-005) -- [ ] T072 [P] [US5] `internal/httpapi/scope_route_table_guard_test.go`: the three routes classified `scopeFiltered` in `getRouteScopes`; `/api/v1/sessions` stays admin-only (FR-045) -- [ ] T073 [P] [US1] `internal/storage/work_sessions_bench_test.go`: list of 1,000 summaries and one timeline page of a 50,000-row session, each against logs of two sizes; the cost does not follow the log size (SC-006) +- [x] T071 [P] [US1] `internal/httpapi/work_sessions_test.go`: list filters `failed`, `include_blocked`, `token`, `client`, `profile`, `run`, `error_class`, `since`, `until`, sort by `last_failure` and `last_activity`, `limit` at most 100; timeline `at=first_failure|failure:|row:|end` with `before` and `after` at most 250 and default 20; current failure index and total over stored failures in reach; with pruned failures the response gives the lifetime count and says earlier failures are no longer stored; bodies omitted unless `include_bodies`; upstream events merged in time order inside the span (SC-005) +- [x] T072 [P] [US5] `internal/httpapi/scope_route_table_guard_test.go`: the three routes classified `scopeFiltered` in `getRouteScopes`; `/api/v1/sessions` stays admin-only (FR-045) +- [x] T073 [P] [US1] `internal/storage/work_sessions_bench_test.go`: list of 1,000 summaries and one timeline page of a 50,000-row session, each against logs of two sizes; the cost does not follow the log size (SC-006) ### Implementation -- [ ] T074 [US1] `internal/storage/work_sessions.go`: list all summaries, timeline page by index range, failure navigation over index keys, event range join per server +- [x] T074 [US1] `internal/storage/work_sessions.go`: list all summaries, timeline page by index range, failure navigation over index keys, event range join per server - [ ] T075 [US5] `internal/httpapi/work_sessions_scope.go` (new): summary projection for the caller and the row-ownership predicate (agent: name and prefix; server user: stored `UserID`), event rows by their own rule -- [ ] T076 [US1] `internal/httpapi/work_sessions.go` (new) and route registration in `internal/httpapi/server.go`: `GET /api/v1/work-sessions`, `/work-sessions/{id}`, `/work-sessions/{id}/timeline`; `internal/contracts` types; `redactForeignIdentity` on loaded rows (makes T070 to T072 pass) +- [x] T076 [US1] `internal/httpapi/work_sessions.go` (new) and route registration in `internal/httpapi/server.go`: `GET /api/v1/work-sessions`, `/work-sessions/{id}`, `/work-sessions/{id}/timeline`; `internal/contracts` types; `redactForeignIdentity` on loaded rows (makes T070 to T072 pass) - [ ] T077 [US1] `make swagger`: regenerate `oas/swagger.yaml` and `oas/docs.go` (FR-047) ## Phase 8: doctor (plan D7; FR-035) -- [ ] T080 [P] [US3] Test first, `internal/management/diagnostics_test.go` and `cmd/mcpproxy/doctor_cmd_test.go`: `ActivityRetention` section with window, shortfall flag, cause, start of the oldest complete session and the settings to raise; one runtime warning line on a shortfall; printed on the all-clear and the issues path; a scoped caller gets no section -- [ ] T081 [US3] `internal/contracts` (`ActivityRetentionReport`), `internal/management/diagnostics.go` (beside `oauth_token_storage`, `:295-308`), `cmd/mcpproxy/doctor_cmd.go`, regenerate swagger (makes T080 pass) +- [x] T080 [P] [US3] Test first, `internal/management/diagnostics_test.go` and `cmd/mcpproxy/doctor_cmd_test.go`: `ActivityRetention` section with window, shortfall flag, cause, start of the oldest complete session and the settings to raise; one runtime warning line on a shortfall; printed on the all-clear and the issues path; a scoped caller gets no section +- [x] T081 [US3] `internal/contracts` (`ActivityRetentionReport`), `internal/management/diagnostics.go` (beside `oauth_token_storage`, `:295-308`), `cmd/mcpproxy/doctor_cmd.go`, regenerate swagger (makes T080 pass) ## Phase 9: PR-1 end to end and docs -- [ ] T090 [US1] `scripts/test-api-e2e.sh`: the morning-after scenario of User Story 1 through REST: an agent token makes calls over REST with `X-MCPProxy-Run`, one fails, the list shows the session as failed and the timeline opens at the failure with the rows before it +- [x] T090 [US1] `scripts/test-api-e2e.sh`: the morning-after scenario of User Story 1 through REST: an agent token makes calls over REST with `X-MCPProxy-Run`, one fails, the list shows the session as failed and the timeline opens at the failure with the rows before it - [ ] T091 [P] [US1] Docs: `docs/features/activity-log.md` (work sessions, upstream events, retention order, shortfall), `docs/api/rest-api.md` (three doors, the header), `docs/configuration.md` (`session_retention_days`, the new `activity_max_records` default), `docs/features/agent-tokens.md` (one token per agent, run name, FR-007) - [ ] T092 [P] `CLAUDE.md` "Recent Changes": one entry for PR-1, written by hand - [ ] T093 Playwright sweep per `docs/development/web-ui-verification.md` (this PR touches `frontend/src/`) @@ -171,7 +171,7 @@ - [ ] T120 `go test -race ./internal/...` and the server-tag run from `CLAUDE.md` (with its `-skip` regex) - [ ] T121 `./scripts/test-api-e2e.sh` - [ ] T122 `/opt/homebrew/bin/golangci-lint run --config .github/.golangci.yml ./...` and the same with `--build-tags server` -- [ ] T123 `scripts/check-upstream-write-sites.sh` and, when the frontend changed, `npm test -- --run` in `frontend/` +- [x] T123 `scripts/check-upstream-write-sites.sh` and, when the frontend changed, `npm test -- --run` in `frontend/` - [ ] T124 Cross-model review with opencode `github-copilot/gpt-6.1-sol`, chunked by file, round cap per `CLAUDE.md` ## Dependencies From 06dcd2b311a8536d7948f6f995310399278a004d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 06:36:10 +0000 Subject: [PATCH 11/11] chore(roadmap): regenerate ROADMAP.md after gardener checkbox sync --- ROADMAP.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 0c1f21f46..ef8984899 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1261,7 +1261,7 @@ graph LR | MCP protocol upgrade to 2026-07-28 revision | In progress | P1 | 40/81 (49%) | [058-mcp-2026-upgrade](./specs/058-mcp-2026-upgrade/) | | | Spec 108 profiles v3: scoped profiles, client binding, scope-aware observability | In progress | P1 | 194/195 (99%) | [108-profiles-v3](./specs/108-profiles-v3/) | | | Spec 109 navigation, scope filters and cross-surface UX consistency | In progress | P1 | 257/258 (100%) | [109-ux-navigation-consistency](./specs/109-ux-navigation-consistency/) | | -| Spec 124 work sessions and the failure timeline | In progress | P1 | 0/74 (0%) | [124-session-failure-timeline](./specs/124-session-failure-timeline/) | | +| Spec 124 work sessions and the failure timeline | In progress | P1 | 40/74 (54%) | [124-session-failure-timeline](./specs/124-session-failure-timeline/) | | | Spec 125 Skills over MCP: catalog, approval gate, read-only agent tools | In progress | P1 | 51/51 (100%) | [125-skills-over-mcp](./specs/125-skills-over-mcp/) | | | 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/) | | @@ -1438,7 +1438,7 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [120-scan-structural-gate](./specs/120-scan-structural-gate/) | — | — | | [122-scanner-skillspector-checks](./specs/122-scanner-skillspector-checks/) | `shipped` | 31/31 (100%) | | [123-oauth-token-encryption](./specs/123-oauth-token-encryption/) | `drafted` | 0/56 (0%) | -| [124-session-failure-timeline](./specs/124-session-failure-timeline/) | `drafted` | 0/74 (0%) | +| [124-session-failure-timeline](./specs/124-session-failure-timeline/) | `in-flight` | 40/74 (54%) | | [125-skills-over-mcp](./specs/125-skills-over-mcp/) | `shipped` | 51/51 (100%) | | [127-profile-argument-rules](./specs/127-profile-argument-rules/) | — | — | | [128-server-list-outcomes](./specs/128-server-list-outcomes/) | — | — |