docs(36): create phase plan

This commit is contained in:
Jakub Zych
2026-11-24 18:56:21 +01:00
parent 4c078005c0
commit 7644786d62
10 changed files with 2510 additions and 14 deletions

View File

@@ -1917,6 +1917,8 @@ Phases execute in numeric order: 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 →
| 32. SEO foundation | 6/6 | In Progress| | | 32. SEO foundation | 6/6 | In Progress| |
| 33. SEO output, audit and content | 16/16 | In Progress| | | 33. SEO output, audit and content | 16/16 | In Progress| |
| 34. Plugin marketplace | 6/6 | In Progress| | | 34. Plugin marketplace | 6/6 | In Progress| |
| 35. Mail templates and layouts editor | 9/9 | Complete | 2026-11-14 |
| 36. Granular MCP OAuth & API token scope picker | 0/4 | Planned | - |
## Backlog ## Backlog
@@ -1995,3 +1997,33 @@ Plans:
**Wave 9** *(gap closure tests, blocked on Wave 8 completion)* **Wave 9** *(gap closure tests, blocked on Wave 8 completion)*
- [x] 35-09-PLAN.md — regression and unit tests for CR-01, WR-01 and WR-05, new names required by `scripts/check-phase35.sh` (plus the IN-03 self-test fix), validation map - [x] 35-09-PLAN.md — regression and unit tests for CR-01, WR-01 and WR-05, new names required by `scripts/check-phase35.sh` (plus the IN-03 self-test fix), validation map
### Phase 36: Granular MCP OAuth & API token scope picker
**Goal:** Scale the administrator MCP OAuth consent screen (`ConnectView.vue`) and personal API token creation dialog (`ApiTokenCreateDialog.vue`) to dozens of plugins and hundreds of granular feature-level scopes, fix the `admin:read` visibility footgun, expose plugin/group metadata on token scopes, and warn at boot when plugins declare backend write MCP tools without a covering `pact.HasTokenScopes` declaration. Decision note: `.planning/notes/2026-11-24-mcp-consent-granular-scope-picker.md`.
**Mode:** mvp
**Depends on:** Phase 32.2 (MCP OAuth with administrator subjects)
**Repos:** `summercms.go` (plus follow-up `HasTokenScopes` additions in `sm-seo-plugin`, `sm-sitemap-plugin` and any other core plugins exposing backend write MCP tools)
**Requirements**: TBD
**Success Criteria** (what must be TRUE):
1. `pact.TokenScope` accepts an optional `Group` field (phrase key or literal, validated when containing `::`) and `cabana.AdminAPITokenScope` additively exposes `plugin_id` and resolved `group` (falling back to plugin name / permission tab / `plugin_id`); `ValidTokenScopeName` stays unchanged and existing plugins without `Group` keep working.
2. Booting an app where a plugin registers backend non-read-only `MCPTool`s not covered by any non-`*` `TokenScope` logs a clear warning identifying the plugin and uncovered tools, without breaking boot.
3. `ConnectView.vue` keeps its `480px` summary card with 3-tier access selection (**Full `*`** | **Read-only `admin:read`** | **Custom**), defaults to `Read-only (admin:read)` when requested and grantable, shows effective-access chips, and opens a dedicated **Customize scopes** modal with search, `All / Selected / Read-only` filters, collapsible plugin/group accordions, per-group quick actions (`Read` / `All` / `Clear`), and an opt-in `admin:read` toggle that visibly locks all `:read` rows (`via admin:read`).
4. `ApiTokenCreateDialog.vue` reuses the same shared `ScopePicker` via an in-dialog view swap (`← Back` / `Apply scopes`, no nested modal overlay) with dark-mode-aware tokens.
5. OpenAPI schema, embedded `boardwalk/dist`, en/pl phrasebook copy, Go unit tests, and Vitest coverage for both `ConnectView` and `ApiTokenCreateDialog` pass green.
**Plans:** 4 plans
Plans:
**Wave 1**
- [ ] 36-01-PLAN.md — Go backend scope metadata (`pact.TokenScope.Group`, `cabana.AdminAPITokenScope` `plugin_id`/`group` + D-16 fallback), `cabana.TokenScopeCovers` + `pier.Mount` boot warning, EN/PL phrasebooks, OpenAPI/TS regen, READMEs & docs
**Wave 2** *(blocked on Wave 1 completion)*
- [ ] 36-02-PLAN.md — Shared 3-tier access selector & `ScopePicker` on `ConnectView.vue` (light-literal modal) and `ApiTokenCreateDialog.vue` (fixed-width in-dialog swap), rebuilt `modules/boardwalk/dist`
**Wave 3** *(blocked on Wave 2 completion)*
- [ ] 36-03-PLAN.md — Core plugin `pact.HasTokenScopes` rollout in `sm-sitemap-plugin` (`sitemap`/`sitemap:read`) and `sm-seo-plugin` (`seo`/`seo:read`) with EN/PL copy, READMEs, and tests
**Wave 4** *(blocked on Wave 3 completion)*
- [ ] 36-04-PLAN.md — Comprehensive Go & Vitest unit/component suites (closing all 7 UI-SPEC backstops), full release gates, human release-tag checkpoint, and `sm-grzybyfunkcjonalne-app` local E2E proof

View File

@@ -1,20 +1,20 @@
--- ---
msd_state_version: "1.0" gsd_state_version: "1.0"
milestone: v1.0 milestone: v1.0
current_phase: "19.3" current_phase: 36
current_phase_name: Framework transport and infrastructure for WavePath current_phase_name: granular-mcp-oauth-api-token-scope-picker
status: planning status: executing
stopped_at: Phase 36 context gathered stopped_at: Phase 36 context gathered
last_updated: "2026-11-24T16:32:14.991Z" last_updated: "2026-11-24T17:54:17.146Z"
last_activity: 2026-11-21 last_activity: 2026-11-21
last_activity_desc: Phase 32.2 complete, transitioned to Phase 19.3 last_activity_desc: Phase 32.2 complete, transitioned to Phase 19.3
state_head: ab64f649b04a2df5699f489cc479a89633def9ce state_head: 4c078005c0ef71c191dde752c5082981bb843f64
progress: progress:
total_phases: 54 total_phases: 54
completed_phases: 38 completed_phases: 38
total_plans: 309 total_plans: 313
completed_plans: 298 completed_plans: 298
gsd_state_version: "1.0" msd_state_version: "1.0"
milestone_name: milestone milestone_name: milestone
--- ---
@@ -29,9 +29,9 @@ See: .planning/PROJECT.md (updated 2026-11-21)
## Current Position ## Current Position
Phase: 19.3 — Framework transport and infrastructure for WavePath Phase: 36 (granular-mcp-oauth-api-token-scope-picker) — READY TO EXECUTE
Plan: Not started Plan: Not started
Status: Ready to plan Status: Ready to execute
Last activity: 2026-11-21 — Phase 32.2 complete, transitioned to Phase 19.3 Last activity: 2026-11-21 — Phase 32.2 complete, transitioned to Phase 19.3
Progress: [████████░░] 77% Progress: [████████░░] 77%

View File

@@ -0,0 +1,311 @@
---
phase: 36-granular-mcp-oauth-api-token-scope-picker
plan: 01
type: execute
wave: 1
depends_on: []
files_modified:
- modules/pact/capabilities.go
- modules/cabana/token_scopes.go
- modules/cabana/account_tokens.go
- modules/cabana/mcp_consent.go
- modules/cabana/token_scopes_export.go
- modules/pier/pier.go
- modules/pier/uncovered_scopes_warning.go
- modules/phrasebook/backend/lang/en/lang.yaml
- modules/phrasebook/backend/lang/pl/lang.yaml
- admin/openapi/admin.json
- admin/src/api/schema.d.ts
- modules/pact/README.md
- modules/cabana/README.md
- modules/pier/README.md
- docs/backend/users-and-permissions.md
- docs/services/mcp.md
autonomous: true
requirements: []
user_setup: []
must_haves:
truths:
- "`pact.TokenScope` accepts an optional `Group string` field (literal text or `::` phrasebook key) while `pact.ValidTokenScopeName` and its regex remain unchanged and `pact.HasTokenScopes` remains explicit with no auto-generation at boot (D-01, D-05, D-14)."
- "`cabana` carries `Group` on `compiledTokenScope` and `validateTokenScopeMessageKeys` fails boot when a non-empty `Group` contains `::` and names a missing phrase key (D-14)."
- "`cabana.AdminAPITokenScope` emits always-present `plugin_id` and `group` JSON fields (no `omitempty`), setting both to `\"\"` for framework scopes (`*`, `admin:read`) and unknown stored scopes across `/account/tokens/scopes`, `/account/tokens`, and `/mcp/consent/{request}` (D-15)."
- "When `TokenScope.Group` is empty on a plugin scope, `cabana` resolves `AdminAPITokenScope.group` in exact D-16 order: (1) `<pluginID>::lang.plugin.name` if present and translated, (2) unanimous non-empty `Tab` across matched `reg.permissions` (translated when containing `::`), (3) raw `PluginID` (D-16)."
- "`cabana.TokenScopeCovers(app, plugins, method, permissions)` evaluates whether at least one non-`*` `TokenScope` covers both HTTP method and all required permissions (returning `false` for empty `permissions`), and `pier.Mount` emits one structured `Warn` log per plugin for uncovered backend non-`GET`/`HEAD` MCP tools without ever breaking boot (D-18)."
- "English and Polish phrasebooks in `modules/phrasebook/backend/lang/{en,pl}/lang.yaml` define all 44 `api_tokens.*` keys (including CLDR plurals `scope_count`, `scope_write_count`, `scope_plugin_count`) and 2 `mcp_connect.*` keys locked in `36-UI-SPEC.md`."
- "`admin/openapi/admin.json`, `admin/src/api/schema.d.ts`, module READMEs (`pact`, `cabana`, `pier`), and `docs/` pages match the new exported Go API and pass `scripts/check-admin-openapi.sh --check`, `TestDocsTree`, and `summer docs:build --check`."
artifacts:
- path: "modules/pact/capabilities.go"
provides: "Optional `Group string` field on `pact.TokenScope`"
contains: "Group string"
- path: "modules/cabana/token_scopes.go"
provides: "`compiledTokenScope.Group` and `validateTokenScopeMessageKeys` check for `scope.Group`"
contains: "scope.Group"
- path: "modules/cabana/account_tokens.go"
provides: "Additive `PluginID`/`Group` on `AdminAPITokenScope` and `resolveScopeGroup` D-16 fallback"
contains: "json:\"plugin_id\""
- path: "modules/cabana/token_scopes_export.go"
provides: "`cabana.TokenScopeCovers` helper for `pier` and plugin tests"
exports: ["TokenScopeCovers"]
- path: "modules/pier/uncovered_scopes_warning.go"
provides: "`warnUncoveredBackendWriteTools` boot-time structured `Warn` per plugin"
contains: "warnUncoveredBackendWriteTools"
- path: "admin/openapi/admin.json"
provides: "Regenerated OpenAPI 3.0 spec with required `plugin_id` and `group` on `cabana.AdminAPITokenScope`"
contains: "\"plugin_id\""
- path: "admin/src/api/schema.d.ts"
provides: "Regenerated TypeScript schema consumed by `admin/src/api/types.ts`"
contains: "plugin_id: string;"
key_links:
- from: "modules/pact/capabilities.go"
to: "modules/cabana/token_scopes.go"
via: "`compileTokenScopes` copies `strings.TrimSpace(scope.Group)` onto `compiledTokenScope.Group` and `validateTokenScopeMessageKeys` validates `::` keys"
pattern: "scope\\.Group"
- from: "modules/cabana/account_tokens.go"
to: "modules/cabana/mcp_consent.go"
via: "Both `/account/tokens/scopes`, `/account/tokens`, and `/mcp/consent/{request}` call `mapCompiledScope(ctx, tr, s.reg, scope)`"
pattern: "mapCompiledScope\\(ctx, tr, s\\.reg, scope\\)"
- from: "modules/pier/pier.go"
to: "modules/cabana/token_scopes_export.go"
via: "`pier.Mount` calls `warnUncoveredBackendWriteTools(app, plugins, cat)` which queries `cabana.TokenScopeCovers`"
pattern: "cabana\\.TokenScopeCovers"
prohibitions:
- "Do NOT alter `pact.ValidTokenScopeName` or `tokenScopeNameRE` (D-01)."
- "Do NOT auto-generate `<plugin>` `TokenScope`s at boot (D-05)."
- "Do NOT add `omitempty` to `AdminAPITokenScope.PluginID` or `AdminAPITokenScope.Group` (D-15)."
- "Do NOT make `pier.Mount` return an error for uncovered backend write MCP tools (D-18)."
- "Do NOT name any consuming application in framework code, module READMEs, or `docs/` (`CLAUDE.md`)."
---
<objective>
**As an** administrator granting MCP OAuth or personal API token access on a multi-plugin SummerCMS site, **I want** every advertised token scope to carry its owning plugin and localized group metadata and **I want** the server to warn at boot when any plugin registers backend write MCP tools without covering `TokenScope`s, **so that** the admin SPA can group hundreds of granular scopes cleanly and operators immediately spot plugins missing `pact.HasTokenScopes`.
**Scope (Plan 36-01, Wave 1):** Framework Go backend changes in `modules/pact`, `modules/cabana`, `modules/pier`, en/pl phrasebook copy in `modules/phrasebook`, OpenAPI/TS schema regeneration (`admin/openapi/admin.json`, `admin/src/api/schema.d.ts`), and module README / `docs/` updates.
*Scope note:* `spec-less probe fallback skipped: phase has no requirement IDs to probe (visible skip)`.
*Reversibility:* `pact.TokenScope.Group` (D-14) and `cabana.AdminAPITokenScope` `plugin_id`/`group` (D-15) are **costly** exported Go/OpenAPI contracts; additive design ensures zero breakage for existing plugins and clients.
</objective>
<execution_context>
@~/.claude/get-shit-done/workflows/execute-plan.md
@~/.claude/get-shit-done/templates/summary.md
</execution_context>
<context>
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-CONTEXT.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-UI-SPEC.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-RESEARCH.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-PATTERNS.md
@CLAUDE.md
</context>
<threat_model>
## Trust Boundaries
| Boundary | Description |
|----------|-------------|
| Plugin declaration (`pact.TokenScope`) → `cabana` boot registry | Untrusted/third-party plugin declarations enter boot compilation and phrasebook validation. |
| `cabana` HTTP endpoints (`/account/tokens/scopes`, `/account/tokens`, `/mcp/consent/{request}`) → Admin SPA | Serialized `AdminAPITokenScope` JSON drives grant decisions in both consent and token-creation UIs. |
| Plugin MCP tool catalog (`pier`) → Operator logs (`diary`) | Boot-time visibility into backend write tools that would otherwise force wildcard `*` grants. |
## STRIDE Threat Register
| Threat ID | Category | Component | Disposition | Mitigation Plan |
|-----------|----------|-----------|-------------|-----------------|
| T-36-01 | Tampering / Information Disclosure | `modules/cabana/token_scopes.go`, `admin/openapi/admin.json`, `admin/src/api/schema.d.ts` | mitigate | Validate `TokenScope.Group` phrase keys containing `::` via `validateTokenScopeMessageKeys` at boot; emit always-present `plugin_id`/`group` strings (no `omitempty`) and enforce schema parity with `scripts/check-admin-openapi.sh --check` so the SPA never sees undefined or drifted fields. |
| T-36-02 | Elevation of Privilege / Repudiation | `modules/cabana/token_scopes_export.go`, `modules/pier/uncovered_scopes_warning.go` | mitigate | `cabana.TokenScopeCovers` excludes wildcard `*` and delegates to `scopeCoversAll`, returning `false` when `permissions` is empty (matching runtime `allowsUnderScope`). `pier.Mount` logs one structured `Warn` per plugin listing uncovered backend write tool names so operators do not silently fall back to `*`. |
| T-36-03 | Spoofing / Elevation of Privilege | `modules/cabana/account_tokens.go` (`mapCompiledScope`, `mapStoredScope`) | mitigate | Force `plugin_id: ""` and `group: ""` for framework scopes (`*`, `admin:read`) and unknown stored scopes so they can never masquerade inside a plugin accordion group; iterate `reg.permissionOrder` deterministically when computing unanimous `Tab` fallback. |
</threat_model>
## Artifacts this phase produces
- **Modified exported struct field (`modules/pact/capabilities.go`):** `pact.TokenScope.Group string`
- **Modified internal struct field & validator (`modules/cabana/token_scopes.go`):** `compiledTokenScope.Group`, `validateTokenScopeMessageKeys` validating `scope.Group`
- **Modified exported DTO fields & helpers (`modules/cabana/account_tokens.go`, `modules/cabana/mcp_consent.go`):** `cabana.AdminAPITokenScope.PluginID` (`json:"plugin_id"`), `cabana.AdminAPITokenScope.Group` (`json:"group"`), `resolveScopeGroup(ctx, tr, reg, scope)`, updated `mapCompiledScope(ctx, tr, reg, scope)`
- **New exported function (`modules/cabana/token_scopes_export.go`):** `cabana.TokenScopeCovers(app *backpack.App, plugins []party.Plugin, method string, permissions []string) bool` and internal `tokenScopeCatalogFor(app, plugins)`
- **New file & function (`modules/pier/uncovered_scopes_warning.go`, wired in `modules/pier/pier.go`):** `warnUncoveredBackendWriteTools(app *backpack.App, plugins []party.Plugin, cat *catalog)`
- **Phrasebook keys (`modules/phrasebook/backend/lang/{en,pl}/lang.yaml`):** 44 new/updated `backend::lang.api_tokens.*` keys (incl. CLDR plurals `scope_count`, `scope_write_count`, `scope_plugin_count`) and 2 `backend::lang.mcp_connect.*` keys (`subline`, `scope_picker_description`)
- **Regenerated contract artifacts:** `admin/openapi/admin.json`, `admin/src/api/schema.d.ts`
- **Updated docs:** `modules/pact/README.md`, `modules/cabana/README.md`, `modules/pier/README.md`, `docs/backend/users-and-permissions.md`, `docs/services/mcp.md`
<tasks>
<task type="tracer">
<name>Task 1: Add `pact.TokenScope.Group`, `cabana` D-16 group resolution, and `AdminAPITokenScope` `plugin_id`/`group` end-to-end</name>
<files>modules/pact/capabilities.go, modules/cabana/token_scopes.go, modules/cabana/account_tokens.go, modules/cabana/mcp_consent.go</files>
<read_first>
- modules/pact/capabilities.go (lines 845-920 — `Permission`, `TokenScope`, `HasTokenScopes`, `ValidTokenScopeName`)
- modules/cabana/token_scopes.go (lines 1-240 — `compiledTokenScope`, `compileTokenScopes`, `validatePluginTokenScope`, `validateTokenScopeMessageKeys`, `scopeMatch`)
- modules/cabana/account_tokens.go (lines 1-45, 165-315 — `AdminAPITokenScope`, `accountTokenScopes`, `mapStoredScope`, `mapCompiledScope`, `resolveScopePhrase`)
- modules/cabana/mcp_consent.go (lines 130-165 — `mcpConsentShow` calling `mapCompiledScope`)
- modules/cabana/registry.go (lines 210-270 — `compilePermissionCatalog`, `reg.permissions`, `reg.permissionOrder`)
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-PATTERNS.md (Patterns 1–3)
</read_first>
<action>
Implement the end-to-end scope metadata slice across `pact` and `cabana` (**Reversibility: costly** for exported `TokenScope.Group` and `AdminAPITokenScope` JSON fields):
1. **`modules/pact/capabilities.go` (D-01, D-05, D-14):**
- Add `Group string` to `pact.TokenScope` right after `Description string` (mirroring `Permission.Tab`).
- Update the doc comment on `TokenScope` to state that `Group` is optional (empty falls back to plugin metadata in `cabana`) and accepts a phrase key containing `"::"` or literal text.
- Keep `HasTokenScopes`, `tokenScopeNameRE`, and `ValidTokenScopeName` completely untouched (D-01, D-05).
2. **`modules/cabana/token_scopes.go` (D-14):**
- Add `Group string` to `compiledTokenScope`.
- In `compileTokenScopes`, copy `Group: strings.TrimSpace(scope.Group)` onto each plugin's `compiledTokenScope`. Keep `PluginID: ""` and `Group: ""` on framework scopes (`*`, `admin:read`).
- In `validateTokenScopeMessageKeys`, check `[]string{scope.Label, scope.Description, scope.Group}` so any non-empty `Group` containing `"::"` must exist in `tr.Has(...)`, while empty `Group` and literal strings pass cleanly.
- Confirm `validatePluginTokenScope` does NOT require `Group` to be non-empty.
3. **`modules/cabana/account_tokens.go` & `modules/cabana/mcp_consent.go` (D-15, D-16, T-36-03):**
- Add `PluginID string \`json:"plugin_id"\`` and `Group string \`json:"group"\`` (no `omitempty`) to `AdminAPITokenScope`.
- Change `mapCompiledScope` signature to `mapCompiledScope(ctx context.Context, tr *phrasebook.Translator, reg *Registry, scope *compiledTokenScope) AdminAPITokenScope`.
- Populate `PluginID: scope.PluginID` and `Group: resolveScopeGroup(ctx, tr, reg, scope)`.
- Implement `resolveScopeGroup(ctx context.Context, tr *phrasebook.Translator, reg *Registry, scope *compiledTokenScope) string` following exact D-16 precedence:
- If `scope == nil || scope.PluginID == ""` (framework scopes `*` and `admin:read`): return `""`.
- Explicit `scope.Group != ""`: if `strings.Contains(scope.Group, "::")`, return `strings.TrimSpace(resolveScopePhrase(ctx, tr, scope.Group, scope.Group))`; otherwise return `scope.Group`.
- Fallback 1: `key := scope.PluginID + "::lang.plugin.name"`. If `tr != nil && tr.Has(key)`, let `s := strings.TrimSpace(tr.Get(ctx, key, nil))`; if `s != "" && s != key`, return `s`.
- Fallback 2: if `reg != nil && len(reg.permissions) > 0`: iterate deterministically over `reg.permissionOrder` (falling back to iterating `reg.permissions` only if `permissionOrder` is empty). For each registered permission `code` matched by any `pattern` in `scope.Permissions` via `scopeMatch(pattern, code) != matchNone`, inspect `p := reg.permissions[code]`. Trim `p.Tab`; if empty, unanimity fails. If `tab` contains `"::"`, resolve via `strings.TrimSpace(resolveScopePhrase(ctx, tr, tab, tab))`; if empty, unanimity fails. If any matched permission has a different resolved `tab` than the first matched permission, unanimity fails. If at least one permission matched and all matched permissions unanimously shared the same non-empty `tab`, return it.
- Fallback 3: return `scope.PluginID`.
- Update all 3 call sites of `mapCompiledScope`:
- `modules/cabana/account_tokens.go` (`s.accountTokenScopes`, pass `s.reg`)
- `modules/cabana/account_tokens.go` (`mapStoredScope`, pass `reg`; unknown stored scope continues returning zero-value `PluginID: ""` and `Group: ""`)
- `modules/cabana/mcp_consent.go` (`s.mcpConsentShow`, pass `s.reg`)
</action>
<acceptance_criteria>
- `modules/pact/capabilities.go` contains `Group` field on `type TokenScope struct` and `tokenScopeNameRE` is unchanged (`git diff modules/pact/capabilities.go` shows no edit to `tokenScopeNameRE` or `ValidTokenScopeName`).
- `modules/cabana/token_scopes.go` checks `scope.Group` inside `validateTokenScopeMessageKeys` and stores `strings.TrimSpace(scope.Group)` on `compiledTokenScope`.
- `modules/cabana/account_tokens.go` defines `PluginID string \`json:"plugin_id"\`` and `Group string \`json:"group"\`` (no `omitempty`) on `AdminAPITokenScope` and implements `resolveScopeGroup` with all 3 D-16 fallback steps.
- All 3 `mapCompiledScope` call sites (`account_tokens.go` x2, `mcp_consent.go` x1) pass `reg` / `s.reg`.
- `go vet ./modules/pact ./modules/cabana && go test -short ./modules/pact ./modules/cabana` passes cleanly.
</acceptance_criteria>
<verify>
<automated>go vet ./modules/pact ./modules/cabana && go test -short ./modules/pact ./modules/cabana</automated>
<fails_when>non-zero exit, compile error, or "FAIL" in output</fails_when>
</verify>
<done>`pact.TokenScope.Group`, `cabana` boot phrase-key validation, D-16 3-step fallback resolution, and `AdminAPITokenScope` `plugin_id`/`group` compile and pass existing short tests.</done>
</task>
<task type="auto">
<name>Task 2: Export `cabana.TokenScopeCovers` and emit `pier.Mount` boot-time warning for uncovered backend write MCP tools (D-18)</name>
<files>modules/cabana/token_scopes_export.go, modules/pier/pier.go, modules/pier/uncovered_scopes_warning.go</files>
<read_first>
- modules/cabana/token_scopes_export.go (full file — `TokenScopeNames`, `TokenScopeLabels`, `tokenCatalogForApp`)
- modules/cabana/token_resolver.go (lines 70-120 — `publishedResolverGuard`)
- modules/cabana/token_scopes.go (lines 245-330 — `allowsUnderScope`, `scopeCoversAll`)
- modules/pier/pier.go (lines 90-170 — `Mount` and `compileCatalog` call site)
- modules/pier/catalog.go (lines 45-80 — `tool` struct fields `name`, `pluginID`, `decl.Permissions`, `method`, `guardName`)
- modules/pier/backend_guard.go (lines 1-40 — `BackendGuard`, existing `cabana` import)
- modules/pier/audit.go (lines 1-30 — `LogComponent`, `logger()`)
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-PATTERNS.md (Patterns 4–5)
</read_first>
<action>
Implement the boot-time coverage check and structured warning (D-18, T-36-02):
1. **`modules/cabana/token_scopes_export.go`:**
- Add internal helper `tokenScopeCatalogFor(app *backpack.App, plugins []party.Plugin) *tokenScopeCatalog`:
1. If `guard := publishedResolverGuard(app); guard != nil && guard.reg != nil && guard.reg.tokenScopes != nil`, return `guard.reg.tokenScopes`.
2. Else if `len(plugins) > 0`, call `cat, err := compileTokenCatalog(plugins)`; if `err == nil`, return `cat` (if `err != nil`, return `nil` without panicking or failing boot).
3. Else return `tokenCatalogForApp(app)`.
- Export `func TokenScopeCovers(app *backpack.App, plugins []party.Plugin, method string, permissions []string) bool`:
- Look up `cat := tokenScopeCatalogFor(app, plugins)`. If `cat == nil`, return `false`.
- Normalize `m := strings.ToUpper(strings.TrimSpace(method))`. If `m == ""`, return `false`.
- Iterate `cat.ordered`:
- Skip `scope.Name == scopeAll` (`*` never satisfies non-`*` coverage).
- Skip scopes where `!scope.Methods[m]`.
- If `scope.Full` (i.e. `admin:read` for `GET`/`HEAD`), return `true`.
- Append `scope.Permissions` to `scopes [][]string`.
- Return `scopeCoversAll(&bouncer.ScopeLimit{Scopes: scopes}, permissions)` (note: `scopeCoversAll` returns `false` when `len(permissions) == 0`, matching runtime `allowsUnderScope`, so backend write tools without `Permissions` are flagged as uncovered).
2. **`modules/pier/uncovered_scopes_warning.go` (new file) & `modules/pier/pier.go`:**
- Create `modules/pier/uncovered_scopes_warning.go` in `package pier` containing `warnUncoveredBackendWriteTools(app *backpack.App, plugins []party.Plugin, cat *catalog)`:
- Return immediately if `cat == nil || len(cat.tools) == 0`.
- Track uncovered tool names per plugin using `byPlugin := map[string][]string{}` and `pluginOrder := []string{}` (preserving first-seen plugin order).
- For each `t` in `cat.tools`:
- Skip unless `t.guardName == BackendGuard`.
- Skip if `t.method == http.MethodGet || t.method == http.MethodHead`.
- If `cabana.TokenScopeCovers(app, plugins, t.method, t.decl.Permissions)`, continue.
- Record `t.name` under `t.pluginID` (if not yet seen, append `t.pluginID` to `pluginOrder`).
- For each `pluginID` in `pluginOrder`:
- Sort `tools := byPlugin[pluginID]` with `slices.Sort(tools)` for deterministic log output.
- Emit ONE structured warning via `logger().Warn(...)`:
`logger().Warn("pier: plugin registers backend write MCP tools not covered by any non-* TokenScope; implement pact.HasTokenScopes so scoped tokens and MCP OAuth grants can call them", "plugin", pluginID, "tools", tools)`
- In `modules/pier/pier.go` inside `Mount`, call `warnUncoveredBackendWriteTools(app, plugins, cat)` immediately after `compileCatalog` succeeds (before returning or mounting handlers). Never return an error from this check (D-18).
</action>
<acceptance_criteria>
- `modules/cabana/token_scopes_export.go` exports `func TokenScopeCovers(app *backpack.App, plugins []party.Plugin, method string, permissions []string) bool`.
- `modules/pier/uncovered_scopes_warning.go` exists and emits `logger().Warn(...)` with `"plugin"` and `"tools"` fields once per plugin with uncovered backend write MCP tools.
- `modules/pier/pier.go` invokes `warnUncoveredBackendWriteTools(app, plugins, cat)` right after `compileCatalog` without adding any error return path.
- `go vet ./modules/cabana ./modules/pier && go test -short ./modules/cabana ./modules/pier` passes cleanly (all existing `pier` tests remain green).
</acceptance_criteria>
<verify>
<automated>go vet ./modules/cabana ./modules/pier && go test -short ./modules/cabana ./modules/pier</automated>
<fails_when>non-zero exit, compile error, or "FAIL" in output</fails_when>
</verify>
<done>`cabana.TokenScopeCovers` and `pier.Mount`'s structured per-plugin boot warning are wired and pass existing `cabana` and `pier` tests.</done>
</task>
<task type="auto">
<name>Task 3: Add en/pl phrasebook copy, regenerate OpenAPI/TS schema, and update module READMEs & docs</name>
<files>modules/phrasebook/backend/lang/en/lang.yaml, modules/phrasebook/backend/lang/pl/lang.yaml, admin/openapi/admin.json, admin/src/api/schema.d.ts, modules/pact/README.md, modules/cabana/README.md, modules/pier/README.md, docs/backend/users-and-permissions.md, docs/services/mcp.md</files>
<read_first>
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-UI-SPEC.md (lines 243-319 — verbatim EN/PL Copywriting Contract)
- modules/phrasebook/backend/lang/en/lang.yaml (lines 285-380, 410-422 — `api_tokens:`, `mcp_connect:`, CLDR plural format)
- modules/phrasebook/backend/lang/pl/lang.yaml (lines 305-402, 430-445 — `api_tokens:`, `mcp_connect:`, CLDR plural format)
- modules/pact/README.md (lines 95-130)
- modules/cabana/README.md (lines 80-115, 275-305)
- modules/pier/README.md (lines 125-160)
- docs/backend/users-and-permissions.md (lines 80-125)
- docs/services/mcp.md (lines 105-150)
</read_first>
<action>
1. **Phrasebook (`modules/phrasebook/backend/lang/en/lang.yaml` and `pl/lang.yaml`):**
- Add all 44 new keys under `api_tokens:` matching `36-UI-SPEC.md` lines 251–296 verbatim, including the 3 CLDR plural maps:
- `scope_count` (`one`/`other` in EN; `one`/`few`/`many`/`other` in PL)
- `scope_write_count` (`one`/`other` in EN; `one`/`few`/`many`/`other` in PL)
- `scope_plugin_count` (`one`/`other` in EN; `one: ":count wtyczce"`, `few: ":count wtyczkach"`, `many: ":count wtyczkach"`, `other: ":count wtyczki"` in PL — locative form after `"w"`!)
- All remaining keys: `access_level`, `tier_full`, `tier_read_only`, `tier_custom`, `scope_customize`, `scope_more`, `scope_summary_line`, `scope_summary_admin_read_only`, `scope_summary_admin_read_plus`, `scope_summary_empty`, `scope_picker_title`, `scope_picker_description`, `scope_picker_apply`, `scope_picker_discard`, `scope_picker_back`, `scope_picker_selected`, `scope_picker_selected_admin_read`, `scope_picker_none_selected`, `scope_search_label`, `scope_search_placeholder`, `scope_search_clear`, `scope_filter_label`, `scope_filter_all`, `scope_filter_selected`, `scope_filter_read_only`, `scope_filter_reset`, `scope_also_admin_read`, `scope_also_admin_read_hint`, `via_admin_read`, `group_select_read`, `group_select_all`, `group_clear`, `group_select_read_named`, `group_select_all_named`, `group_clear_named`, `scope_empty_search_title`, `scope_empty_search_body`, `scope_empty_selected_title`, `scope_empty_selected_body`, `scope_empty_readonly_title`, `scope_empty_readonly_body`.
- Update `mcp_connect.subline` and add `mcp_connect.scope_picker_description` in both `en/lang.yaml` and `pl/lang.yaml` verbatim per `36-UI-SPEC.md` lines 300–303.
- Preserve all existing keys under `api_tokens:` and `mcp_connect:` so nothing breaks.
2. **OpenAPI & TypeScript Schema Regeneration:**
- Run `scripts/check-admin-openapi.sh` (without `--check`) to regenerate `admin/openapi/admin.json` and `admin/src/api/schema.d.ts` with required `plugin_id: string` and `group: string` on `cabana.AdminAPITokenScope`.
- Verify with `scripts/check-admin-openapi.sh --check`.
3. **Module READMEs & `docs/` (`CLAUDE.md` Documentation rules):**
- `modules/pact/README.md`: document optional `Group` field on `pact.TokenScope` (phrase key containing `::` or literal text, matching `Permission.Tab`).
- `modules/cabana/README.md`: document `PluginID` (`plugin_id`) and `Group` (`group`) on `cabana.AdminAPITokenScope` (including D-16 fallback resolution order) and add `cabana.TokenScopeCovers` to the API reference.
- `modules/pier/README.md`: document that `pier.Mount` checks backend write MCP tools against non-`*` `TokenScope`s via `cabana.TokenScopeCovers` and logs one structured `Warn` per plugin with uncovered tools without failing boot.
- `docs/backend/users-and-permissions.md`: document optional `TokenScope.Group` (and its `::` phrase-key boot check) and `plugin_id`/`group` fallback resolution.
- `docs/services/mcp.md`: note that backend write MCP tools should be covered by `pact.HasTokenScopes` and that `pier` logs a boot-time warning per plugin when any backend non-`GET`/`HEAD` tool is uncovered.
- Keep every cited Go identifier exact and neutral (never name any consuming application). Run `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree'` and `go run ./cmd/summer docs:build --check`.
</action>
<acceptance_criteria>
- `modules/phrasebook/backend/lang/en/lang.yaml` and `pl/lang.yaml` parse cleanly under `go test -short ./modules/phrasebook` and contain all 46 new/updated keys (`access_level`, `via_admin_read`, `scope_plugin_count`, `mcp_connect.scope_picker_description`, etc.).
- `admin/openapi/admin.json` and `admin/src/api/schema.d.ts` both include required `plugin_id` and `group` properties on `cabana.AdminAPITokenScope`, and `scripts/check-admin-openapi.sh --check` exits 0.
- `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree' -count=1` and `go run ./cmd/summer docs:build --check` both exit 0.
- `go vet ./... && go test -short ./modules/pact ./modules/cabana ./modules/pier ./modules/phrasebook` exits 0.
</acceptance_criteria>
<verify>
<automated>go vet ./... && go test -short ./modules/pact ./modules/cabana ./modules/pier ./modules/phrasebook && scripts/check-admin-openapi.sh --check && go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree' -count=1 && go run ./cmd/summer docs:build --check</automated>
<fails_when>non-zero exit, OpenAPI drift message, docs identifier error, or "FAIL" in output</fails_when>
</verify>
<done>EN/PL phrasebook copy, OpenAPI/TS schema, and all module READMEs + `docs/` pages are updated and pass all Go, OpenAPI, and docs gates.</done>
</task>
</tasks>
<verification>
Run full Wave 1 smoke & contract verification before advancing to Wave 2:
- `go vet ./... && go test -short ./modules/pact ./modules/cabana ./modules/pier ./modules/phrasebook`
- `scripts/check-admin-openapi.sh --check`
- `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree' -count=1 && go run ./cmd/summer docs:build --check`
</verification>
<success_criteria>
- `pact.TokenScope.Group`, `cabana` compilation/validation/D-16 fallback, `AdminAPITokenScope` `plugin_id`/`group`, `cabana.TokenScopeCovers`, and `pier.Mount` boot warning are all implemented and green.
- All 46 EN/PL phrasebook keys match `36-UI-SPEC.md` verbatim.
- `admin/openapi/admin.json` and `admin/src/api/schema.d.ts` are regenerated and pass `--check`.
- All module READMEs and `docs/` pages pass `TestDocsTree` and `docs:build --check`.
</success_criteria>
<output>
After completion, create `.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-01-SUMMARY.md`
</output>

View File

@@ -0,0 +1,322 @@
---
phase: 36-granular-mcp-oauth-api-token-scope-picker
plan: 02
type: execute
wave: 2
depends_on: ["36-01"]
files_modified:
- admin/src/styles/main.css
- admin/src/app/scopeCatalog.ts
- admin/src/components/scopes/useScopeSelection.ts
- admin/src/components/scopes/ScopeAccessControl.vue
- admin/src/components/scopes/ScopePicker.vue
- admin/src/views/ConnectView.vue
- admin/src/components/account/ApiTokenCreateDialog.vue
- admin/tests/fixtures/lang.json
- admin/tests/views/ConnectView.test.ts
- admin/tests/smoke/connect.smoke.test.ts
- admin/tests/account/ApiTokenCreateDialog.test.ts
- admin/tests/account/ApiTokensPanel.test.ts
- modules/boardwalk/dist/index.html
autonomous: true
requirements: []
user_setup: []
must_haves:
truths:
- "`ConnectView` consent card loading skeleton (`aria-busy=\"true\"`) mirrors client mark + segmented tier bar + summary box with no buttons until loaded."
- "`ApiTokenCreateDialog` scope catalog loading state renders a skeleton segmented tier bar + summary box while `GET /account/tokens/scopes` is in flight and keeps **Create token** disabled."
- "`ConnectView` and `ApiTokenCreateDialog` submit loading states disable fieldsets and buttons with a `LoaderCircle` spinner and prevent opening the Customize picker while busy."
- "`ConnectView` with zero grantable scopes displays the existing `none_grantable` alert in place of `ScopeAccessControl` and offers only **Deny** (D-03)."
- "`ScopeAccessControl` in `Custom` with 0 selected scopes displays actionable `scope_summary_empty` copy + **Customize scopes…** button and keeps **Allow** / **Create token** disabled (D-02)."
- "`ScopePicker` search with 0 matches renders a dashed empty block with `scope_empty_search_title`, `scope_empty_search_body` naming `:query`, and a **Clear search** button."
- "`ScopePicker` `Selected` filter with 0 selected scopes renders a dashed empty block with `scope_empty_selected_*` and a **Show all scopes** button."
- "`ScopePicker` `Read-only` filter with 0 read-only scopes renders a dashed empty block with `scope_empty_readonly_*` and a **Show all scopes** button."
- "`ScopePicker` with an empty draft disables **Apply scopes** and renders `scope_picker_none_selected` in the live footer so the user must pick at least one scope or discard (D-11)."
- "`ConnectView` preserves all Phase 32.2 load/submit/404/401/422/bad-URI error states, and 422 `scopes_required` highlights `ScopeAccessControl` in `border-danger` (D-03)."
- "`ApiTokenCreateDialog` preserves its `scopes_failed` alert and highlights `ScopeAccessControl` invalid + moves focus to it on 422 `errors.scopes`."
- "Small scope catalogs (`<= 3` groups or `<= 12` plugin scopes) expand all accordions automatically on picker open (D-07)."
- "Large scope catalogs (`> 3` groups and `> 12` plugin scopes) expand only groups with active selections on picker open (all collapsed if none selected), and typing a search auto-expands all matching groups without destroying pre-search expand state (D-07)."
- "Custom summary box displays elevated-first chips (`admin:read` if ON, then write scopes, then read-only scopes when `admin:read` is OFF), capped at 6 + clickable `+N more` chip + `\"X scopes across Y plugins\"` subtitle (D-04, D-06)."
- "Missing tiers are omitted from `RadioGroupRoot`; if no plugin scopes exist beyond `*` and `admin:read`, `Custom` tier is hidden (D-03); `ApiTokenCreateDialog` falls back to `Full (*)` when `admin:read` is absent (D-08); `ConnectView` opens in `Custom` when the client requested only a narrow plugin subset (D-03)."
- "Two plugins with identical translated `group` labels render separate flat accordions keyed by `${plugin_id}\\0${group}` (never colliding), sorted alphabetically with `Intl.Collator` and tie-broken by `plugin_id`, preserving declared intra-group scope order (D-01, D-17)."
- "Scope counts, write-scope counts, and plugin counts evaluate full CLDR plural keys (`one`/`few`/`many`/`other` in PL, `one`/`other` in EN) via `tc()`."
- "On mobile viewports (`< 640px`), `ConnectView` Customize scopes modal renders as a `100dvh` full-screen sheet with sticky search/filter header, independently scrollable accordion body, and sticky footer (D-10)."
- "On desktop viewports (`>= 640px`), `ConnectView` Customize modal is capped at `max-w-[640px] max-h-[85dvh]` and `ApiTokenCreateDialog` stays fixed at `max-w-[560px] max-h-[calc(100vh-32px)]` with sticky header/footer and zero double scrollbars (D-10, D-13)."
- "Long plugin group names, scope labels, mono codes, and descriptions use `[overflow-wrap:anywhere]`, and summary chips truncate safely inside `max-w-full` pills with full scope name in `:title`."
- "In `<html class=\"dark\">`, `ApiTokenCreateDialog` inherits `.dark` semantic tokens automatically while `ConnectView`'s card and portaled Customize modal apply `.connect-light-surface` (defined in `admin/src/styles/main.css` `@layer components`, pinning both `--c-*` and `--color-*` aliases) so they stay strictly light (D-12)."
- "Opening `ScopePicker` focuses the search input; closing restores focus to **Customize scopes…** (or checked tier radio); pressing Escape in `ApiTokenCreateDialog`'s swapped picker view discards draft (reverting tier if auto-opened empty) and returns to the token form preserving `name` and `expires` without closing the dialog (D-09, D-11, D-13); `mod+s`/`mod+enter` is inactive inside the picker view."
- "`ApiTokensPanel.vue` remains backwards-compatible with additive `plugin_id` and `group` fields on `AdminAPITokenScope` (D-15) and `scripts/check-admin-dist.sh` passes after rebuilding `modules/boardwalk/dist`."
artifacts:
- path: "admin/src/styles/main.css"
provides: "`.connect-light-surface` in `@layer components` pinning both `--c-*` and `--color-*` aliases"
contains: ".connect-light-surface"
- path: "admin/src/app/scopeCatalog.ts"
provides: "Pure catalog partitioning, `(plugin_id, group)` grouping/collation, query matching, smart expand, elevated-first summary builder, submitted-scope serializer, initial state resolver"
exports: ["partitionCatalog", "groupPluginScopes", "matchesScopeQuery", "isEffectivelySelected", "computeDefaultExpanded", "buildSummaryModel", "computeSubmittedScopes", "resolveInitialState"]
- path: "admin/src/components/scopes/useScopeSelection.ts"
provides: "Reactive 3-tier scope state, tier memory, auto-open empty Custom, draft/apply/discard composable"
exports: ["useScopeSelection"]
- path: "admin/src/components/scopes/ScopeAccessControl.vue"
provides: "Shared 3-tier `RadioGroupRoot` + compact effective-access summary box"
contains: "data-access-tiers"
- path: "admin/src/components/scopes/ScopePicker.vue"
provides: "Shared sticky-header / flat-accordion / sticky-footer scope picker with opt-in `admin:read` toggle and `via admin:read` lock"
contains: "data-scope-picker"
- path: "admin/src/views/ConnectView.vue"
provides: "Option D standalone `480px` consent card + responsive `.connect-light-surface` Customize modal"
contains: "data-scope-picker-dialog"
- path: "admin/src/components/account/ApiTokenCreateDialog.vue"
provides: "Option D personal token dialog with `Read-only` default and fixed `max-w-[560px]` in-dialog `ScopePicker` view swap"
contains: "data-action=\"scope-picker-back\""
key_links:
- from: "admin/src/views/ConnectView.vue"
to: "admin/src/components/scopes/ScopePicker.vue"
via: "Reka `DialogPortal` with `.connect-light-surface` on `DialogOverlay` and `DialogContent`, state managed by `useScopeSelection(scopes, 'connect')`"
pattern: "useScopeSelection"
- from: "admin/src/components/account/ApiTokenCreateDialog.vue"
to: "admin/src/components/scopes/ScopePicker.vue"
via: "In-dialog `v-if=\"step === 1 && pickerOpen\"` view swap inside fixed `max-w-[560px]` `DialogContent`, Escape intercepted to call `onPickerCancel()`"
pattern: "useScopeSelection"
- from: "admin/src/components/scopes/ScopePicker.vue"
to: "admin/src/app/scopeCatalog.ts"
via: "`groupPluginScopes`, `matchesScopeQuery`, `isEffectivelySelected`, `computeDefaultExpanded`, `buildSummaryModel`"
pattern: "groupPluginScopes"
prohibitions:
- "Do NOT add any new npm dependencies or new `:root`/`.dark` CSS custom properties (`36-UI-SPEC.md`)."
- "Do NOT define `.connect-light-surface` in Vue `<style scoped>` (Reka `DialogPortal` teleports to `document.body`)."
- "Do NOT nest a second modal overlay inside `ApiTokenCreateDialog.vue` (D-02, D-13)."
- "Do NOT include `admin:read` in submitted Custom scopes unless the opt-in toggle is explicitly checked (D-04)."
- "Do NOT auto-focus or attach hotkeys to Allow/Deny on `ConnectView.vue`, and do NOT render server-delivered scope text via `v-html`."
---
<objective>
**As an** administrator approving an MCP connector on `/connect` or minting a personal API token in My Account, **I want** a calm 3-tier access selector defaulting to `Read-only (admin:read)` plus a searchable, grouped `ScopePicker` with an explicit opt-in `admin:read` lock toggle, **so that** I can safely grant exact feature-level access across dozens of plugins without accidentally leaking read access to sensitive resources.
**Scope (Plan 36-02, Wave 2):** Shared scope selection primitives (`main.css` `.connect-light-surface`, `scopeCatalog.ts`, `useScopeSelection.ts`, `ScopeAccessControl.vue`, `ScopePicker.vue`), full integration in `ConnectView.vue` and `ApiTokenCreateDialog.vue`, `ApiTokensPanel.vue` compatibility check, fixture/type updates in existing test files + `lang.json`, and rebuilt embedded `modules/boardwalk/dist` verified by `scripts/check-admin-dist.sh`. Comprehensive new unit/component test suites land in Plan 36-04 per `CLAUDE.md` rule 2.
</objective>
<execution_context>
@~/.claude/get-shit-done/workflows/execute-plan.md
@~/.claude/get-shit-done/templates/summary.md
</execution_context>
<context>
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-CONTEXT.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-UI-SPEC.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-RESEARCH.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-PATTERNS.md
@CLAUDE.md
</context>
<threat_model>
## Trust Boundaries
| Boundary | Description |
|----------|-------------|
| Backend JSON (`AdminAPITokenScope.label`, `.description`, `.group`, `client.name`) → Vue DOM | Server-supplied plugin metadata renders inside consent and token-creation dialogs. |
| User tier/checkbox interaction → `POST /mcp/consent/{request}` & `POST /account/tokens` | Selected scopes define the OAuth grant or `g15_` token's `bouncer.ScopeLimit`. |
| Keyboard shortcuts (`Escape`, `mod+s`, `mod+enter`) → Dialog form submission | Accidental hotkey trigger could mint a token or approve OAuth before finishing scope customization. |
## STRIDE Threat Register
| Threat ID | Category | Component | Disposition | Mitigation Plan |
|-----------|----------|-----------|-------------|-----------------|
| T-36-04 | Elevation of Privilege (HIGH) | `admin/src/app/scopeCatalog.ts`, `admin/src/components/scopes/ScopePicker.vue` | mitigate | In `Custom` tier, `adminRead` defaults to `false` and `computeSubmittedScopes` omits `admin:read` unless explicitly opted in (D-04). When toggled ON, every `read_only` row is locked-checked with a visible `Lock` icon + `via admin:read` badge, per-group `Read` is disabled, `Clear` only unticks unlocked write scopes, and `admin:read` appears as the first summary chip. |
| T-36-05 | Elevation of Privilege / Tampering (HIGH) | `admin/src/views/ConnectView.vue` | mitigate | Preserve all Phase 32.2 invariants (D-03): default to `Read-only (admin:read)` when grantable, hide ungrantable scopes, never auto-allow when `consent_required === false`, never auto-focus or bind hotkeys to Allow/Deny, validate redirect destinations with `safeDestination` + `FORBIDDEN_PROTOCOLS`, and navigate via `window.location.assign`. |
| T-36-06 | Tampering / XSS | `admin/src/components/account/ApiTokenCreateDialog.vue`, `ScopeAccessControl.vue`, `ScopePicker.vue` | mitigate | Render all server-delivered strings (`label`, `description`, `group`, `plugin_id`, `client.name`) strictly through Vue text interpolation (zero `v-html`). Keep the `mod+s mod+enter` submit button inside `v-if="step === 1 && !pickerOpen"` so hotkeys cannot submit while editing scopes, and intercept `Escape` in picker view to discard draft without closing the dialog (D-13). |
</threat_model>
## Artifacts this phase produces
- **CSS utility class (`admin/src/styles/main.css`):** `.connect-light-surface` inside `@layer components` re-declaring both `--c-*` and `--color-*: var(--c-*)`
- **New pure module (`admin/src/app/scopeCatalog.ts`):** types `AccessTier`, `ScopeFilter`, `ScopeGroup`, `CustomScopeSelection`, `ScopeSummaryChip`, `PartitionedCatalog`, `SummaryModel`, `InitialScopeState`; functions `partitionCatalog`, `groupPluginScopes`, `matchesScopeQuery`, `isEffectivelySelected`, `computeDefaultExpanded`, `buildSummaryModel`, `computeSubmittedScopes`, `resolveInitialState`
- **New composable (`admin/src/components/scopes/useScopeSelection.ts`):** `useScopeSelection(catalogRef, mode)` exposing `availableTiers`, `tier`, `custom`, `pickerOpen`, `draftAdminRead`, `draftScopes`, `submittedScopes`, `summary`, `canSubmitScopes`, `reset`, `selectTier`, `openPicker`, `applyPicker`, `discardPicker`
- **New Vue components:** `admin/src/components/scopes/ScopeAccessControl.vue` (exposing `focusPrimaryControl()`), `admin/src/components/scopes/ScopePicker.vue` (exposing `focusSearch()`)
- **Modified Vue surfaces:** `admin/src/views/ConnectView.vue`, `admin/src/components/account/ApiTokenCreateDialog.vue`
- **Updated test fixtures & embedded SPA build:** `admin/tests/fixtures/lang.json`, updated existing Vitest fixture files (`ConnectView.test.ts`, `connect.smoke.test.ts`, `ApiTokenCreateDialog.test.ts`, `ApiTokensPanel.test.ts`), rebuilt `modules/boardwalk/dist/*`
<tasks>
<task type="tracer">
<name>Task 1: Build `.connect-light-surface`, shared scope module (`scopeCatalog`, `useScopeSelection`, `ScopeAccessControl`, `ScopePicker`), and wire `ConnectView.vue`</name>
<files>admin/src/styles/main.css, admin/src/app/scopeCatalog.ts, admin/src/components/scopes/useScopeSelection.ts, admin/src/components/scopes/ScopeAccessControl.vue, admin/src/components/scopes/ScopePicker.vue, admin/src/views/ConnectView.vue</files>
<read_first>
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-UI-SPEC.md (lines 150-241 for `.connect-light-surface` & colors, lines 322-548 for C1–C4 contracts)
- admin/src/styles/main.css (lines 1-140, 185-230 — `@theme`, `:root`, `.dark`, `@layer components`)
- admin/src/views/ConnectView.vue (full file — Phase 32.2 states, invariants, focus management)
- admin/src/api/types.ts (lines 1-90 — `AdminAPITokenScope`, `MCPConsent`)
- admin/src/app/i18n.ts (lines 1-140 — `t`, `tc`, `currentLocale`)
- admin/src/components/form/control.ts (lines 45-70 — `controlClass`)
- admin/src/components/ui/confirm.ts (lines 1-85 — composable pattern)
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-PATTERNS.md (Patterns 7–9)
</read_first>
<action>
Implement the shared scope module and wire it end-to-end into `ConnectView.vue` matching `36-UI-SPEC.md` C1–C4 verbatim:
1. **`admin/src/styles/main.css` (D-12):**
- Inside `@layer components`, add `.connect-light-surface` declaring `color-scheme: light`, all 17 light-literal `--c-*` variables (`--c-bg` through `--c-overlay`), AND re-declaring all 17 `--color-*: var(--c-*)` aliases verbatim from `36-UI-SPEC.md` lines 165–202 so Tailwind v4 `@theme` utilities stay light even under `<html class="dark">` and inside `DialogPortal`. Never put this in `<style scoped>`.
2. **`admin/src/app/scopeCatalog.ts` (D-01, D-03, D-04, D-06, D-07, D-08, D-17):**
- Import `AdminAPITokenScope` from `../api/types`.
- Export types: `AccessTier`, `ScopeFilter`, `ScopeGroup`, `CustomScopeSelection`, `ScopeSummaryChip`, `PartitionedCatalog`, `SummaryModel`, `InitialScopeState`.
- Export pure functions per `36-UI-SPEC.md` C1:
- `partitionCatalog(catalog)` → `{ fullScope, adminReadScope, pluginScopes }`.
- `groupPluginScopes(pluginScopes, locale, fallbackGroupLabel)` → flat groups keyed `${scope.plugin_id}\0${scope.group}`, preserving intra-group catalog order, sorted by `new Intl.Collator(locale, { sensitivity: 'base' }).compare(a.label, b.label)` with tie-break `a.pluginId.localeCompare(b.pluginId)`.
- `matchesScopeQuery(scope, groupLabel, query)` → normalized case-insensitive substring across `name`, `label`, `description`, `plugin_id`, `groupLabel`.
- `isEffectivelySelected(scope, selection)` → `selection.scopes.has(scope.name) || (selection.adminRead && scope.read_only)`.
- `computeDefaultExpanded(groups, totalPluginScopes, selection, searching)` → all expanded if `searching` OR `groups.length <= 3 || totalPluginScopes <= 12`; else only groups with at least one effectively selected scope.
- `buildSummaryModel(catalog, selection, maxVisible = 6)` → elevated-first chips (`admin:read` if ON → selected non-`read_only` plugin scopes → selected `read_only` plugin scopes only when `!selection.adminRead`), `visible` sliced to `maxVisible`, `overflowCount`, `selectedWriteCount`, `selectedPluginCount`, `distinctPluginCount` (unique `scope.plugin_id || scope.group || scope.name` among counted plugin scopes).
- `computeSubmittedScopes(tier, catalog, custom)` → `'full'` → `['*']`, `'read_only'` → `['admin:read']`, `'custom'` → if `custom.adminRead && adminReadScope` return `['admin:read', ...selectedWriteScopes]`, else return `selectedPluginScopes` (never leaking `admin:read` when unchecked, T-36-04).
- `resolveInitialState(catalog, mode: 'connect' | 'token')` → exact D-03 (`'connect'`) and D-08 (`'token'`) rules.
3. **`admin/src/components/scopes/useScopeSelection.ts` (D-03, D-09, D-11):**
- Implement `useScopeSelection(catalog: Ref<readonly AdminAPITokenScope[]>, mode: 'connect' | 'token')`.
- Manage `tier`, `custom` (`{ adminRead: boolean; scopes: Set<string> }`), `pickerOpen`, `draftAdminRead`, `draftScopes`, `autoOpenedFrom`.
- `availableTiers`: order `['full', 'read_only', 'custom']` filtered by `fullScope`, `adminReadScope`, `pluginScopes.length > 0` (hides `Custom` when no plugin scopes exist, D-03).
- `reset(nextCatalog?)`: initializes `tier` & `custom` via `resolveInitialState`, closes picker, clears `autoOpenedFrom`.
- `selectTier(next)`: preserves `custom` in memory when switching away; if switching to `'custom'` with empty `custom` (`!adminRead && scopes.size === 0`), sets `autoOpenedFrom = previousTier`, sets `tier = 'custom'`, and calls `openPicker()` immediately (D-09); if `custom` is non-empty, restores it on the summary card without reopening the picker.
- `openPicker()`, `applyPicker()`, `discardPicker()` (reverts `tier = autoOpenedFrom` if non-null, D-11).
4. **`admin/src/components/scopes/ScopeAccessControl.vue` (D-02, D-06, D-12):**
- Implement per `36-UI-SPEC.md` C2 using only semantic Tailwind utilities (`bg-surface`, `bg-subtle`, `border-border`, `border-border-strong`, `text-text`, `text-muted`, `hover:bg-hover`, `border-danger`).
- `RadioGroupRoot` (`data-access-tiers`) with `RadioGroupItem` (`:data-access-tier="item"`), `grid-cols-3` or `grid-cols-2`, hidden when `availableTiers.length <= 1`.
- Compact summary box (`data-scope-summary`, `role="region"`, `:aria-invalid="invalid ? 'true' : undefined"`): renders `full`, `read_only`, or `custom` view (with CLDR plural subtitle via `tc()`, **Customize scopes…** button `data-action="customize-scopes"`, elevated-first chips `data-summary-chip`, clickable `+N more` button `data-action="customize-scopes-more"`, or `scope_summary_empty`).
- `defineExpose({ focusPrimaryControl })`.
5. **`admin/src/components/scopes/ScopePicker.vue` (D-01, D-04, D-07, D-11, D-17):**
- Implement per `36-UI-SPEC.md` C3 using only semantic Tailwind utilities and `@lucide/vue` icons (`Search`, `X`, `ChevronDown`, `ChevronRight`, `Lock`).
- Sticky header: search input (`data-scope-search`, `controlClass(false)` + `h-input pl-10 pr-10`) + clear button (`data-action="clear-scope-search"`), filter pills (`data-scope-filter="all" | "selected" | "read_only"` with live catalog counts), opt-in `admin:read` toggle banner (`data-admin-read-toggle`, `data-admin-read-checkbox`).
- Scrollable accordion body: 3 specific dashed empty states (`data-scope-picker-empty` with **Clear search** / **Show all scopes**), flat `(plugin_id, group)` sections (`data-scope-group`) with toggle button (`data-scope-group-toggle`, `aria-expanded`, `aria-controls`), count badge (`data-scope-group-count`, `tabular-nums`), per-group `Read`/`All`/`Clear` buttons (`data-group-action="read" | "all" | "clear"` with translated `:group` `aria-label`s; `Read` disabled and `Clear` selective when `draftAdminRead` is ON), and scope rows (`:data-scope="scope.name"`, `read_only` locked-checked + `Lock` + `data-via-admin-read` badge when `draftAdminRead` is ON; preserving pre-existing `:read` ticks in `draftScopes` if toggled back OFF).
- Sticky footer: `aria-live="polite"` `data-scope-picker-summary` using `tc()`, secondary cancel button (`data-action="scope-picker-discard"`), primary **Apply scopes** button (`data-action="scope-picker-apply"`, disabled when 0 effective scopes or `disabled`).
- `defineExpose({ focusSearch })`.
6. **`admin/src/views/ConnectView.vue` (D-02, D-03, D-10, D-11, D-12, T-36-05):**
- Apply `.connect-light-surface` on the consent card container.
- Replace flat checkboxes + `initialTicks` with `useScopeSelection(scopes, 'connect')` + `<ScopeAccessControl id-prefix="connect" ... />`.
- Update the `loading` skeleton scope block to mirror the segmented tier bar + summary box.
- Add the Reka `Dialog` Customize modal (`DialogRoot`, `DialogPortal`, `DialogOverlay` with `.connect-light-surface`, `DialogContent` with `data-scope-picker-dialog` + `.connect-light-surface` + `h-[100dvh]` mobile / `sm:max-w-[640px] sm:max-h-[85dvh]` desktop classes per `36-UI-SPEC.md` C4) hosting `<ScopePicker>` with focus-to-search on open and focus-restore on close.
- Preserve ALL Phase 32.2 invariants: 5 states, `none_grantable`, `offline_access` default ticked, `safeDestination`, `window.location.assign`, `switchAccount`, no auto-allow, no initial focus or hotkey on Allow/Deny.
</action>
<acceptance_criteria>
- `admin/src/styles/main.css` defines `.connect-light-surface` inside `@layer components` with both `--c-*` and `--color-*` declarations.
- `admin/src/app/scopeCatalog.ts`, `admin/src/components/scopes/useScopeSelection.ts`, `ScopeAccessControl.vue`, and `ScopePicker.vue` exist and match every `data-*` hook and behavior in `36-UI-SPEC.md` C1–C3.
- `admin/src/views/ConnectView.vue` applies `.connect-light-surface` on both the consent card and the portaled `DialogOverlay`/`DialogContent`, renders `<ScopeAccessControl>` and `<ScopePicker>`, and preserves zero `v-html` usage (`! grep -q 'v-html' admin/src/components/scopes/*.vue admin/src/views/ConnectView.vue`).
- `npm --prefix admin run typecheck` compiles all new source files without errors (note: existing test files are updated in Task 3; verify `npx --prefix admin vue-tsc --noEmit` on `src` or check Task 3 immediately after Task 2).
</acceptance_criteria>
<verify>
<automated>test -f admin/src/app/scopeCatalog.ts && test -f admin/src/components/scopes/useScopeSelection.ts && test -f admin/src/components/scopes/ScopeAccessControl.vue && test -f admin/src/components/scopes/ScopePicker.vue && grep -q '\.connect-light-surface' admin/src/styles/main.css && grep -q 'data-scope-picker-dialog' admin/src/views/ConnectView.vue && ! grep -q 'v-html' admin/src/components/scopes/*.vue admin/src/views/ConnectView.vue</automated>
<fails_when>non-zero exit or missing file/selector or `v-html` found</fails_when>
</verify>
<done>Shared scope selection primitives and `ConnectView.vue` Option D consent card + light-literal responsive Customize modal are implemented.</done>
</task>
<task type="auto">
<name>Task 2: Integrate `ScopeAccessControl` and in-dialog `ScopePicker` view swap into `ApiTokenCreateDialog.vue` and confirm `ApiTokensPanel.vue` compatibility</name>
<files>admin/src/components/account/ApiTokenCreateDialog.vue</files>
<read_first>
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-UI-SPEC.md (lines 550-590 — C5 & C6 contracts)
- admin/src/components/account/ApiTokenCreateDialog.vue (full file — Step 1/Step 2, `onEscapeKey`, `onOpenChange`, `focusFirstInvalid`, `mod+s mod+enter`)
- admin/src/components/account/ApiTokensPanel.vue (lines 255-305 — confirm read-only compatibility with additive `plugin_id`/`group`)
- admin/src/components/scopes/useScopeSelection.ts
- admin/src/components/scopes/ScopeAccessControl.vue
- admin/src/components/scopes/ScopePicker.vue
</read_first>
<action>
Update `admin/src/components/account/ApiTokenCreateDialog.vue` per `36-UI-SPEC.md` C5 (D-02, D-08, D-11, D-12, D-13, T-36-06):
1. Replace flat `checked` / `toggleScope` / `selectedScopes` with `useScopeSelection(scopes, 'token')` so after `GET /account/tokens/scopes` resolves, the dialog initializes to `Read-only (admin:read)` (falling back to `Full (*)` when `admin:read` is absent, D-08).
2. Keep `DialogContent` fixed at `max-w-[560px]` across all views (`step === 1 && !pickerOpen`, `step === 1 && pickerOpen`, and `step === 2`) with ZERO nested modal overlay (D-02, D-13).
3. When `step === 1 && !pickerOpen` (token form):
- Keep Name input, Expiration `RadioGroupRoot`, and Step 1 footer (**Discard token** + **Create token** with `hotkey="mod+s mod+enter"` — unmounted automatically when `pickerOpen` is true so `mod+s`/`mod+enter` cannot submit while customizing scopes, T-36-06).
- Replace the flat scope checkbox list with `<ScopeAccessControl ref="scopeAccessRef" id-prefix="api-token" ... :invalid="Boolean(errors.scopes)" @customize="onPickerOpen" />`.
- Update the scope loading skeleton to mirror `ScopeAccessControl` (`h-10 rounded-inner bg-skel` + `rounded-inner border border-border bg-subtle p-4` with two skeleton bars).
- Keep `scopesFailed` alert (`api_tokens.scopes_failed`), 422 validation handling (`focusFirstInvalid` focusing `scopeAccessRef.focusPrimaryControl()` when `errors.scopes` is set), and `onSubmit()` posting `{ name, expires, scopes: submittedScopes.value }`.
4. When `step === 1 && pickerOpen` (swapped `ScopePicker` view):
- Render the dedicated edge-to-edge header (`shrink-0 flex items-start gap-4 border-b border-border bg-surface p-4`) with:
- Back button (`type="button"`, `data-action="scope-picker-back"`, `<ArrowLeft :size="16" aria-hidden="true" />` + `t('backend::lang.api_tokens.scope_picker_back')`, `@click="onPickerCancel"`).
- `DialogTitle` (`api_tokens.scope_picker_title`) and `DialogDescription` (`api_tokens.scope_picker_description`).
- Close `X` button (`data-action="close"`, calls `requestClose()`).
- Render `<ScopePicker ref="scopePickerRef" :catalog="scopes" v-model:draft-admin-read="draftAdminRead" v-model:draft-scopes="draftScopes" :cancel-label="t('backend::lang.api_tokens.scope_picker_back')" :disabled="busy" @apply="onPickerApply" @cancel="onPickerCancel" />` directly inside `DialogContent` (inheriting `.dark` / `:root` semantic tokens automatically, D-12).
5. Escape & focus handoff (D-11, D-13):
- In `onEscapeKey(event)`: when `step.value === 1 && pickerOpen.value`, call `event.preventDefault()` and `void onPickerCancel()` (discards draft, reverts tier if auto-opened empty, returns to token form preserving `name` and `expires` without closing the dialog).
- `onPickerOpen()` opens picker and focuses `scopePickerRef.focusSearch()` after `nextTick()`.
- `onPickerApply()` commits draft, clears `errors.scopes`, returns to token form preserving `name` and `expires`, and focuses `scopeAccessRef.focusPrimaryControl()` after `nextTick()`.
- `onPickerCancel()` discards draft (with auto-open tier revert), returns to token form preserving `name` and `expires`, and focuses `scopeAccessRef.focusPrimaryControl()` after `nextTick()`.
- Resetting the dialog on close/open sets `pickerOpen = false` and resets `useScopeSelection`.
6. Leave Step 2 (show-once plaintext token, copy, uncopied-close `ConfirmDialog`, unmount cleanup) and `ApiTokensPanel.vue` completely untouched (D-15).
</action>
<acceptance_criteria>
- `admin/src/components/account/ApiTokenCreateDialog.vue` uses `useScopeSelection`, `<ScopeAccessControl>`, and `<ScopePicker>` inside the single `max-w-[560px]` `DialogContent` (only one `DialogOverlay` in template).
- `onEscapeKey` intercepts Escape when `step.value === 1 && pickerOpen.value` with `event.preventDefault()` and calls `onPickerCancel()`.
- The `hotkey="mod+s mod+enter"` submit button is rendered only when `step === 1 && !pickerOpen`.
- `git diff admin/src/components/account/ApiTokensPanel.vue` is empty (confirmed compatible untouched).
</acceptance_criteria>
<verify>
<automated>grep -q 'data-action="scope-picker-back"' admin/src/components/account/ApiTokenCreateDialog.vue && grep -q 'useScopeSelection' admin/src/components/account/ApiTokenCreateDialog.vue && test "$(grep -c '<DialogOverlay' admin/src/components/account/ApiTokenCreateDialog.vue)" -eq 1 && test -z "$(git diff admin/src/components/account/ApiTokensPanel.vue)"</automated>
<fails_when>non-zero exit, missing back action/composable, multiple DialogOverlay tags, or unexpected diff in ApiTokensPanel.vue</fails_when>
</verify>
<done>`ApiTokenCreateDialog.vue` implements the Option D 3-tier access control and fixed-width in-dialog `ScopePicker` view swap cleanly.</done>
</task>
<task type="auto">
<name>Task 3: Update test fixtures (`lang.json` + existing 4 Vitest suites), typecheck, rebuild `modules/boardwalk/dist`, and pass `check-admin-dist.sh`</name>
<files>admin/tests/fixtures/lang.json, admin/tests/views/ConnectView.test.ts, admin/tests/smoke/connect.smoke.test.ts, admin/tests/account/ApiTokenCreateDialog.test.ts, admin/tests/account/ApiTokensPanel.test.ts, modules/boardwalk/dist/index.html</files>
<read_first>
- admin/tests/fixtures/lang.json (lines 1-60 and search for `api_tokens` / `mcp_connect`)
- admin/tests/views/ConnectView.test.ts (full file — scope fixtures and D-03 assertions)
- admin/tests/smoke/connect.smoke.test.ts (full file — scope fixtures and default allow)
- admin/tests/account/ApiTokenCreateDialog.test.ts (full file — scope fixtures and D-08 default)
- admin/tests/account/ApiTokensPanel.test.ts (full file — scope fixtures and dialog rules)
- modules/phrasebook/backend/lang/pl/lang.yaml (lines 307-415 — exact Polish strings & CLDR plurals for `lang.json`)
- scripts/check-admin-dist.sh
</read_first>
<action>
Keep existing tests green and rebuild the committed embedded SPA bundle (full new unit/component coverage for all 7 `backstop` rows lands in Plan 36-04 per `CLAUDE.md` rule 2):
1. **`admin/tests/fixtures/lang.json`:**
- Add every new/updated Polish key under `backend::lang.api_tokens.*` (including the 3 CLDR plural objects `scope_count`, `scope_write_count`, `scope_plugin_count` in the exact structure `admin/src/app/i18n.ts` expects — match existing `richeditor.removed_elements` in `lang.json`) and `backend::lang.mcp_connect.subline` + `backend::lang.mcp_connect.scope_picker_description`.
2. **Update the 4 existing Vitest files for required `plugin_id`/`group` types and D-03 / D-08 behavior:**
- `admin/tests/views/ConnectView.test.ts`: add `plugin_id` (`""` for `*`/`admin:read`, `"acme.blog"` for `acme`) and `group` (`""` for `*`/`admin:read`, `"Acme"` for `acme`) on all scope fixtures; update default allow assertion from `['admin:read', 'acme']` to `['admin:read']` (D-03) and update scope-toggling tests to use `[data-access-tier="..."]` / `[data-action="customize-scopes"]` / `[data-scope-picker-dialog]`.
- `admin/tests/smoke/connect.smoke.test.ts`: add `plugin_id`/`group` to fixtures and update default allow assertion to `['admin:read']` (D-03).
- `admin/tests/account/ApiTokenCreateDialog.test.ts`: add `plugin_id`/`group` to fixtures; update tests that previously assumed 0 preselected scopes to reflect the new safe D-08 `Read-only (admin:read)` default and tier/picker interactions.
- `admin/tests/account/ApiTokensPanel.test.ts`: add `plugin_id`/`group` to fixtures; update `dialog rules` tests to interact via `[data-access-tier="full"]`, default `read_only`, and `[data-action="customize-scopes"]`.
3. **Typecheck, smoke test, build & dist gate:**
- Run `npm --prefix admin run typecheck`.
- Run `npm --prefix admin run test -- tests/smoke/connect.smoke.test.ts tests/views/ConnectView.test.ts tests/account/ApiTokenCreateDialog.test.ts tests/account/ApiTokensPanel.test.ts`.
- Run `npm --prefix admin run build` to rebuild `modules/boardwalk/dist/`.
- Run `scripts/check-admin-dist.sh` to confirm committed `modules/boardwalk/dist` matches a fresh build cleanly.
</action>
<acceptance_criteria>
- `admin/tests/fixtures/lang.json` is valid JSON containing all new Polish `api_tokens.*` and `mcp_connect.*` keys including the 3 CLDR plural maps.
- `npm --prefix admin run typecheck` exits 0 with zero TypeScript errors across both `src/` and `tests/`.
- `npm --prefix admin run test -- tests/smoke/connect.smoke.test.ts tests/views/ConnectView.test.ts tests/account/ApiTokenCreateDialog.test.ts tests/account/ApiTokensPanel.test.ts` exits 0 with zero failed tests.
- `npm --prefix admin run build && scripts/check-admin-dist.sh` exits 0.
</acceptance_criteria>
<verify>
<automated>npm --prefix admin run typecheck && npm --prefix admin run test -- tests/smoke/connect.smoke.test.ts tests/views/ConnectView.test.ts tests/account/ApiTokenCreateDialog.test.ts tests/account/ApiTokensPanel.test.ts && npm --prefix admin run build && scripts/check-admin-dist.sh</automated>
<fails_when>non-zero exit, vue-tsc error, Vitest test mismatch, or check-admin-dist.sh diff</fails_when>
</verify>
<done>Admin SPA typechecks, passes updated existing suites, rebuilds `modules/boardwalk/dist`, and passes `scripts/check-admin-dist.sh`.</done>
</task>
</tasks>
<verification>
Run Wave 2 SPA & embedded dist gates:
- `npm --prefix admin run typecheck`
- `npm --prefix admin run test -- tests/smoke/connect.smoke.test.ts tests/views/ConnectView.test.ts tests/account/ApiTokenCreateDialog.test.ts tests/account/ApiTokensPanel.test.ts`
- `scripts/check-admin-dist.sh`
</verification>
<success_criteria>
- Shared `scopeCatalog.ts`, `useScopeSelection.ts`, `ScopeAccessControl.vue`, and `ScopePicker.vue` implement every Option D behavior (D-01..D-04, D-06..D-13, D-17) and all 22 `covered` UI Considerations from `36-UI-SPEC.md`.
- `ConnectView.vue` keeps its `480px` light-literal card and adds the responsive `.connect-light-surface` Customize modal (`100dvh` mobile / `max-w-[640px] max-h-[85dvh]` desktop).
- `ApiTokenCreateDialog.vue` defaults to `Read-only (admin:read)`, swaps in-dialog at fixed `max-w-[560px]` with Escape returning to the form preserving `name`/`expires`, and inherits dark-mode semantic tokens.
- `modules/boardwalk/dist` is rebuilt and passes `scripts/check-admin-dist.sh`.
</success_criteria>
<output>
After completion, create `.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-02-SUMMARY.md`
</output>

View File

@@ -0,0 +1,230 @@
---
phase: 36-granular-mcp-oauth-api-token-scope-picker
plan: 03
type: execute
wave: 3
depends_on: ["36-01", "36-02"]
files_modified:
- ../sm-sitemap-plugin/token_scopes.go
- ../sm-sitemap-plugin/lang/en/lang.yaml
- ../sm-sitemap-plugin/lang/pl/lang.yaml
- ../sm-sitemap-plugin/README.md
- ../sm-sitemap-plugin/token_scopes_test.go
- ../sm-seo-plugin/token_scopes.go
- ../sm-seo-plugin/lang/en/lang.yaml
- ../sm-seo-plugin/lang/pl/lang.yaml
- ../sm-seo-plugin/README.md
- ../sm-seo-plugin/token_scopes_test.go
autonomous: true
requirements: []
user_setup: []
must_haves:
truths:
- "`sm-sitemap-plugin` explicitly implements `pact.HasTokenScopes` declaring `sitemap` (all methods, `golem15.sitemap.*`) and `sitemap:read` (`GET`/`HEAD`, `golem15.sitemap.*`) with localized EN/PL labels and descriptions (D-05, D-19)."
- "`sm-seo-plugin` explicitly implements `pact.HasTokenScopes` declaring `seo` (all methods, `golem15.seo.*`) and `seo:read` (`GET`/`HEAD`, `golem15.seo.*`) with localized EN/PL labels and descriptions (D-05, D-19)."
- "Both plugins cover 100% of their backend write MCP tools (`2` write tools in `sm-sitemap-plugin`, `26` write tools in `sm-seo-plugin`) under `cabana.TokenScopeCovers`, emitting zero uncovered-tool `Warn` logs from `pier.Mount` (D-18, D-19)."
- "Scoped read-only principals (`sitemap:read`, `seo:read`) allow `GET` requests and are denied on write requests (`POST`/`PUT`/`DELETE`), while full plugin scopes (`sitemap`, `seo`) allow both reads and writes within the plugin's own permissions."
- "Both `../sm-sitemap-plugin` and `../sm-seo-plugin` pass `go vet ./...` and `go test ./...` cleanly with updated `README.md` API documentation."
artifacts:
- path: "../sm-sitemap-plugin/token_scopes.go"
provides: "`(*Plugin).TokenScopes()` implementing `pact.HasTokenScopes` with `sitemap` and `sitemap:read`"
exports: ["TokenScopes"]
- path: "../sm-sitemap-plugin/token_scopes_test.go"
provides: "Unit tests for scope declarations, EN/PL YAML keys, `cabana.TokenScopeCovers`, zero `pier.Mount` warnings, and read/write enforcement"
contains: "TestTokenScopes"
- path: "../sm-seo-plugin/token_scopes.go"
provides: "`(*Plugin).TokenScopes()` implementing `pact.HasTokenScopes` with `seo` and `seo:read`"
exports: ["TokenScopes"]
- path: "../sm-seo-plugin/token_scopes_test.go"
provides: "Unit tests for scope declarations, EN/PL YAML keys, `cabana.TokenScopeCovers` across all 26 write MCP tools, zero `pier.Mount` warnings, and read/write enforcement"
contains: "TestTokenScopes"
key_links:
- from: "../sm-sitemap-plugin/token_scopes.go"
to: "../sm-sitemap-plugin/lang/en/lang.yaml"
via: "Phrase keys `golem15.sitemap::lang.scopes.{sitemap,sitemap_description,sitemap_read,sitemap_read_description}` validated by `cabana`"
pattern: "golem15\\.sitemap::lang\\.scopes\\."
- from: "../sm-seo-plugin/token_scopes.go"
to: "../sm-seo-plugin/lang/en/lang.yaml"
via: "Phrase keys `golem15.seo::lang.scopes.{seo,seo_description,seo_read,seo_read_description}` validated by `cabana`"
pattern: "golem15\\.seo::lang\\.scopes\\."
prohibitions:
- "Do NOT grant write HTTP methods (`POST`/`PUT`/`PATCH`/`DELETE`) on `sitemap:read` or `seo:read`."
- "Do NOT broaden `Permissions` beyond `golem15.sitemap.*` / `golem15.seo.*`."
- "Do NOT tag or push either plugin repository in this plan (tagging happens only after user approval at Plan 36-04's decision checkpoint)."
---
<objective>
Implement explicit `pact.HasTokenScopes` declarations across the two core plugins identified by the 26-plugin audit as exposing uncovered backend write MCP tools: `../sm-sitemap-plugin` (2 write + 1 GET tools) and `../sm-seo-plugin` (26 write + 15 GET tools).
**Scope (Plan 36-03, Wave 3 — runs after Plan 36-02 so `modules/boardwalk/dist` is settled before sibling plugin Go tests compile `boardwalk`):** Add `token_scopes.go`, EN/PL phrasebook copy, `README.md` updates, and unit/coverage tests (`token_scopes_test.go`) in both sibling plugin repositories. Because both plugins already define `<pluginID>::lang.plugin.name` (`"Sitemap"` / `"Mapy witryny"` and `"SEO"` / `"SEO"`), D-16 fallback 1 resolves `AdminAPITokenScope.group` automatically without requiring explicit `Group` overrides.
*Reversibility:* **costly** (D-19) — scope names (`sitemap`, `sitemap:read`, `seo`, `seo:read`) become part of published OAuth `scopes_supported` and persisted API token grants.
</objective>
<execution_context>
@~/.claude/get-shit-done/workflows/execute-plan.md
@~/.claude/get-shit-done/templates/summary.md
</execution_context>
<context>
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-CONTEXT.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-RESEARCH.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-PATTERNS.md
@CLAUDE.md
</context>
<threat_model>
## Trust Boundaries
| Boundary | Description |
|----------|-------------|
| Plugin `TokenScopes()` declaration → `cabana` scope enforcement & OAuth `scopes_supported` | Misconfigured `Permissions` or `Methods` would widen token grants beyond the plugin or allow writes on `:read` tokens. |
| Plugin `lang/{en,pl}/lang.yaml` → `cabana` boot validator (`validateTokenScopeMessageKeys`) | Missing or misspelled phrasebook keys break application boot for every consumer mounting the plugin. |
## STRIDE Threat Register
| Threat ID | Category | Component | Disposition | Mitigation Plan |
|-----------|----------|-----------|-------------|-----------------|
| T-36-07 | Elevation of Privilege (HIGH) | `../sm-sitemap-plugin/token_scopes.go`, `../sm-seo-plugin/token_scopes.go` | mitigate | Restrict `Permissions` strictly to `golem15.sitemap.*` and `golem15.seo.*`, restrict `:read` scopes strictly to `GET`/`HEAD`, and assert in `token_scopes_test.go` that `:read` tokens succeed on `GET` and are denied (`403` / `cabana.Allows == false`) on write methods. |
| T-36-08 | Denial of Service / Boot Failure | `../sm-sitemap-plugin/lang/{en,pl}/lang.yaml`, `../sm-seo-plugin/lang/{en,pl}/lang.yaml` | mitigate | Verify every declared `Label` and `Description` phrase key exists in both `en/lang.yaml` and `pl/lang.yaml` via `goccy/go-yaml` parsing and compile the plugin through `cabana` + `pier.Mount` in `token_scopes_test.go`. |
</threat_model>
## Artifacts this phase produces
- **In `../sm-sitemap-plugin`:**
- `../sm-sitemap-plugin/token_scopes.go` (`(*Plugin).TokenScopes()` → `sitemap`, `sitemap:read`)
- `../sm-sitemap-plugin/lang/en/lang.yaml` & `../sm-sitemap-plugin/lang/pl/lang.yaml` (`scopes.sitemap*` keys)
- `../sm-sitemap-plugin/README.md` (`TokenScopes` API documentation)
- `../sm-sitemap-plugin/token_scopes_test.go` (`TestTokenScopes`, `TestTokenScopesCoverMCPTools`, `TestTokenScopesReadWriteEnforcement`)
- **In `../sm-seo-plugin`:**
- `../sm-seo-plugin/token_scopes.go` (`(*Plugin).TokenScopes()` → `seo`, `seo:read`)
- `../sm-seo-plugin/lang/en/lang.yaml` & `../sm-seo-plugin/lang/pl/lang.yaml` (`scopes.seo*` keys)
- `../sm-seo-plugin/README.md` (`TokenScopes` API documentation)
- `../sm-seo-plugin/token_scopes_test.go` (`TestTokenScopes`, `TestTokenScopesCoverMCPTools`, `TestTokenScopesReadWriteEnforcement`)
<tasks>
<task type="auto">
<name>Task 1: Implement `pact.HasTokenScopes` (`sitemap`, `sitemap:read`), en/pl copy, README, and tests in `../sm-sitemap-plugin`</name>
<files>../sm-sitemap-plugin/token_scopes.go, ../sm-sitemap-plugin/lang/en/lang.yaml, ../sm-sitemap-plugin/lang/pl/lang.yaml, ../sm-sitemap-plugin/README.md, ../sm-sitemap-plugin/token_scopes_test.go</files>
<read_first>
- ../sm-journal-plugin/token_scopes.go (reference `pact.HasTokenScopes` implementation)
- ../sm-journal-plugin/token_scopes_test.go (reference test layout)
- ../sm-sitemap-plugin/plugin.go
- ../sm-sitemap-plugin/mcp.go
- ../sm-sitemap-plugin/controllers/api/auth.go
- ../sm-sitemap-plugin/lang/en/lang.yaml
- ../sm-sitemap-plugin/lang/pl/lang.yaml
- ../sm-sitemap-plugin/README.md
- ../sm-sitemap-plugin/go.mod
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-RESEARCH.md (section 3.3)
</read_first>
<action>
Implement explicit `pact.HasTokenScopes` in `../sm-sitemap-plugin` (D-05, D-19, **Reversibility: costly**):
1. **Create `../sm-sitemap-plugin/token_scopes.go`:**
- Compile-time assertion `var _ pact.HasTokenScopes = (*Plugin)(nil)`.
- `func (p *Plugin) TokenScopes() []pact.TokenScope` returning:
- `sitemap`: `Label: "golem15.sitemap::lang.scopes.sitemap"`, `Description: "golem15.sitemap::lang.scopes.sitemap_description"`, `Permissions: []string{"golem15.sitemap.*"}`, `Methods: []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}`.
- `sitemap:read`: `Label: "golem15.sitemap::lang.scopes.sitemap_read"`, `Description: "golem15.sitemap::lang.scopes.sitemap_read_description"`, `Permissions: []string{"golem15.sitemap.*"}`, `Methods: []string{"GET", "HEAD"}`.
- Leave `Group` empty so D-16 fallback 1 resolves `golem15.sitemap::lang.plugin.name` (`"Sitemap"` / `"Mapy witryny"`).
2. **Update `../sm-sitemap-plugin/lang/en/lang.yaml` and `../sm-sitemap-plugin/lang/pl/lang.yaml`:**
- Add `scopes:` block matching `36-RESEARCH.md` lines 473–483 (`sitemap`, `sitemap_description`, `sitemap_read`, `sitemap_read_description` in EN and PL).
3. **Update `../sm-sitemap-plugin/README.md`:**
- Document `TokenScopes` (`sitemap`, `sitemap:read`) in the API reference / capabilities section matching existing README style.
4. **Create `../sm-sitemap-plugin/token_scopes_test.go`:**
- Assert `(*Plugin).TokenScopes()` returns `sitemap` and `sitemap:read` with exact `Permissions` and `Methods` (and `sitemap:read` never includes write methods, T-36-07).
- Parse `lang/en/lang.yaml` and `lang/pl/lang.yaml` with `github.com/goccy/go-yaml` and assert every declared `Label` and `Description` key resolves to a non-empty string in both locales (T-36-08).
- Assert `cabana.TokenScopeNames` includes `"sitemap"` and `"sitemap:read"`.
- Assert `cabana.TokenScopeCovers` returns `true` for every non-`GET`/`HEAD` backend tool from `(*Plugin).MCPTools()` (`sitemap_update_settings`, `sitemap_rebuild`), AND mount `pier.Mount` with `(*Plugin)` capturing `slog.Default()` logs to verify ZERO `"not covered by any non-* TokenScope"` warnings are emitted (D-18).
- Assert scoped principal enforcement: a principal built with `cabana.ScopeLimitFor` for `["sitemap"]` is allowed on `PUT` and `POST` for `golem15.sitemap.access_definitions`, whereas `["sitemap:read"]` is allowed on `GET` and denied on `PUT`/`POST` (T-36-07).
5. **Note on `go.mod`:** Keep the existing local `replace git.golem15.com/golem15/summercms => ../summercms.go` line working during Wave 3 development; version bumps to the tagged `summercms v0.6.8` happen only after user approval at Plan 36-04's checkpoint.
</action>
<acceptance_criteria>
- `../sm-sitemap-plugin/token_scopes.go` declares `var _ pact.HasTokenScopes = (*Plugin)(nil)` with `sitemap` and `sitemap:read`.
- `../sm-sitemap-plugin/lang/en/lang.yaml` and `pl/lang.yaml` define all 4 `scopes.*` keys.
- `../sm-sitemap-plugin/token_scopes_test.go` tests YAML keys, `cabana.TokenScopeCovers`, zero `pier.Mount` warnings, and read-vs-write enforcement.
- `(cd ../sm-sitemap-plugin && go vet ./... && go test ./...)` exits 0.
</acceptance_criteria>
<verify>
<automated>(cd ../sm-sitemap-plugin && go vet ./... && go test -count=1 ./...)</automated>
<fails_when>non-zero exit, compile error, or "FAIL" in output</fails_when>
</verify>
<done>`../sm-sitemap-plugin` implements `pact.HasTokenScopes` (`sitemap`, `sitemap:read`), covers all backend write MCP tools with zero `pier.Mount` warnings, and passes `go vet` + `go test`.</done>
</task>
<task type="auto">
<name>Task 2: Implement `pact.HasTokenScopes` (`seo`, `seo:read`), en/pl copy, README, and tests in `../sm-seo-plugin`</name>
<files>../sm-seo-plugin/token_scopes.go, ../sm-seo-plugin/lang/en/lang.yaml, ../sm-seo-plugin/lang/pl/lang.yaml, ../sm-seo-plugin/README.md, ../sm-seo-plugin/token_scopes_test.go</files>
<read_first>
- ../sm-journal-plugin/token_scopes.go
- ../sm-sitemap-plugin/token_scopes.go
- ../sm-sitemap-plugin/token_scopes_test.go
- ../sm-seo-plugin/plugin.go
- ../sm-seo-plugin/mcp.go
- ../sm-seo-plugin/controllers/api/auth.go
- ../sm-seo-plugin/lang/en/lang.yaml
- ../sm-seo-plugin/lang/pl/lang.yaml
- ../sm-seo-plugin/README.md
- ../sm-seo-plugin/go.mod
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-RESEARCH.md (section 3.2)
</read_first>
<action>
Implement explicit `pact.HasTokenScopes` in `../sm-seo-plugin` (D-05, D-19, **Reversibility: costly**). Because `sm-seo-plugin` uses a single permission (`golem15.seo.manage`) across all 41 tools, declare the clean `seo` + `seo:read` pair per D-19:
1. **Create `../sm-seo-plugin/token_scopes.go`:**
- Compile-time assertion `var _ pact.HasTokenScopes = (*Plugin)(nil)`.
- `func (p *Plugin) TokenScopes() []pact.TokenScope` returning:
- `seo`: `Label: "golem15.seo::lang.scopes.seo"`, `Description: "golem15.seo::lang.scopes.seo_description"`, `Permissions: []string{"golem15.seo.*"}`, `Methods: []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}`.
- `seo:read`: `Label: "golem15.seo::lang.scopes.seo_read"`, `Description: "golem15.seo::lang.scopes.seo_read_description"`, `Permissions: []string{"golem15.seo.*"}`, `Methods: []string{"GET", "HEAD"}`.
- Leave `Group` empty so D-16 fallback 1 resolves `golem15.seo::lang.plugin.name` (`"SEO"` in EN and PL).
2. **Update `../sm-seo-plugin/lang/en/lang.yaml` and `../sm-seo-plugin/lang/pl/lang.yaml`:**
- Add `scopes:` block matching `36-RESEARCH.md` lines 416–426 (`seo`, `seo_description`, `seo_read`, `seo_read_description` in EN and PL).
3. **Update `../sm-seo-plugin/README.md`:**
- Document `TokenScopes` (`seo`, `seo:read`) in the API reference / capabilities section matching existing README style.
4. **Create `../sm-seo-plugin/token_scopes_test.go`:**
- Assert `(*Plugin).TokenScopes()` returns `seo` and `seo:read` with exact `Permissions` and `Methods` (`seo:read` strictly `GET`/`HEAD`, T-36-07).
- Parse `lang/en/lang.yaml` and `lang/pl/lang.yaml` with `github.com/goccy/go-yaml` and assert every declared `Label` and `Description` key resolves to a non-empty string in both locales (T-36-08).
- Assert `cabana.TokenScopeNames` includes `"seo"` and `"seo:read"`.
- Iterate all 41 tools from `(*Plugin).MCPTools()` and assert `cabana.TokenScopeCovers` returns `true` for every write tool (confirming ≥ 26 write tools covered), AND mount `pier.Mount` capturing `slog.Default()` logs to verify ZERO `"not covered by any non-* TokenScope"` warnings are emitted (D-18).
- Assert scoped principal enforcement: `["seo"]` allows `GET`/`POST`/`PUT`/`DELETE` for `golem15.seo.manage`, whereas `["seo:read"]` allows `GET` and denies `POST`/`PUT`/`DELETE` (T-36-07).
5. **Note on `go.mod`:** Keep the existing local `replace` lines working during development; bumping `summercms` and `sm-sitemap-plugin` requirements happens only after user approval at Plan 36-04's release checkpoint.
</action>
<acceptance_criteria>
- `../sm-seo-plugin/token_scopes.go` declares `var _ pact.HasTokenScopes = (*Plugin)(nil)` with `seo` and `seo:read`.
- `../sm-seo-plugin/lang/en/lang.yaml` and `pl/lang.yaml` define all 4 `scopes.*` keys.
- `../sm-seo-plugin/token_scopes_test.go` tests YAML keys, `cabana.TokenScopeCovers` across all write MCP tools, zero `pier.Mount` warnings, and read-vs-write enforcement.
- `(cd ../sm-seo-plugin && go vet ./... && go test ./...)` exits 0.
</acceptance_criteria>
<verify>
<automated>(cd ../sm-seo-plugin && go vet ./... && go test -count=1 ./...)</automated>
<fails_when>non-zero exit, compile error, or "FAIL" in output</fails_when>
</verify>
<done>`../sm-seo-plugin` implements `pact.HasTokenScopes` (`seo`, `seo:read`), covers all 26 backend write MCP tools with zero `pier.Mount` warnings, and passes `go vet` + `go test`.</done>
</task>
</tasks>
<verification>
Run both sibling plugin test suites from the workspace root:
- `(cd ../sm-sitemap-plugin && go vet ./... && go test -count=1 ./...)`
- `(cd ../sm-seo-plugin && go vet ./... && go test -count=1 ./...)`
</verification>
<success_criteria>
- Both `../sm-sitemap-plugin` and `../sm-seo-plugin` declare explicit `pact.HasTokenScopes` with EN/PL copy and README updates.
- Both plugins emit zero `pier.Mount` uncovered-write-tool warnings and pass `go vet ./... && go test ./...`.
- Neither repository is tagged or pushed before user approval in Plan 36-04.
</success_criteria>
<output>
After completion, create `.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-03-SUMMARY.md`
</output>

View File

@@ -0,0 +1,387 @@
---
phase: 36-granular-mcp-oauth-api-token-scope-picker
plan: 04
type: execute
wave: 4
depends_on: ["36-02", "36-03"]
files_modified:
- modules/cabana/token_scopes_test.go
- modules/cabana/token_scope_names_test.go
- modules/cabana/account_tokens_test.go
- modules/cabana/mcp_admin_consent_test.go
- modules/pier/uncovered_scopes_warning_test.go
- admin/tests/app/scopeCatalog.test.ts
- admin/tests/scopes/ScopeAccessControl.test.ts
- admin/tests/scopes/ScopePicker.test.ts
- admin/tests/views/ConnectView.test.ts
- admin/tests/smoke/connect.smoke.test.ts
- admin/tests/account/ApiTokenCreateDialog.test.ts
- admin/tests/account/ApiTokensPanel.test.ts
- ../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh
- ../sm-grzybyfunkcjonalne-app/go.mod
- ../sm-sitemap-plugin/go.mod
- ../sm-seo-plugin/go.mod
autonomous: false
requirements: []
user_setup: []
must_haves:
truths:
- "Go unit and integration tests verify `pact.TokenScope.Group` (literal, valid phrase key, missing `::` phrase key boot error), D-16 3-step fallback resolution (`Group` → `::lang.plugin.name` → unanimous permission `Tab` → `PluginID`, `\"\"` for framework/unknown), `AdminAPITokenScope` JSON wire fields on `/account/tokens/scopes`, `/account/tokens`, and `/mcp/consent/{request}`, `cabana.TokenScopeCovers`, and `pier.Mount` structured boot warnings (D-14, D-15, D-16, D-18)."
- statement: "Initial default tiers on ConnectView and ApiTokenCreateDialog: both default to Read-only (admin:read) when grantable; ConnectView opens narrow subset in Custom, *-only in Full, and hides Custom when no plugin scopes exist; ApiTokenCreateDialog falls back to Full (*) when admin:read is absent (D-03, D-08)."
verification: backstop
- statement: "admin:read toggle & lock semantics (PII footgun fix): Custom omits admin:read by default; enabling opt-in toggle locks every read_only row checked with via admin:read badge, disables per-group Read, makes Clear untick only unlocked scopes, renders admin:read chip first, and submits ['admin:read', ...writes]; toggling OFF restores prior :read ticks (D-04, D-17)."
verification: backstop
- statement: "Tier memory, auto-open empty Custom, and draft/discard revert: clicking Custom when empty auto-opens picker; Discard/Escape reverts to previous tier; applying then switching to Read-only and back to Custom restores saved selection in memory without reopening picker (D-09, D-11)."
verification: backstop
- statement: "Grouping, sorting, search, filter pills, and smart expand: (plugin_id, group) key prevents collisions, alphabetical group sort with plugin_id tie-break preserves intra-group scope order, search matches plugin/group/label/code/description and auto-expands matches, filter pills show live counts, small vs large catalog expand rules hold (D-01, D-07, D-17)."
verification: backstop
- statement: "ApiTokenCreateDialog in-dialog swap + Escape preservation: clicking Customize scopes swaps view in place (zero second dialog overlay), pressing Escape discards draft and returns to token form with name and expires intact, and mod+s does not submit while in picker view (D-02, D-13)."
verification: backstop
- statement: "ConnectView modal light-surface & mobile classes: portaled DialogOverlay and DialogContent carry .connect-light-surface, mobile full-screen sheet classes (h-[100dvh]), and desktop sm:max-w-[640px] sm:max-h-[85dvh] (D-10, D-12)."
verification: backstop
- statement: "Elevated-first chip cap at 6 + +N more: admin:read and write scopes sort ahead of read-only scopes; 8 selected scopes render 6 chips + clickable +2 more chip that opens ScopePicker (D-06)."
verification: backstop
- "All framework release verification gates pass green: `go vet ./...`, `go test ./...`, `scripts/check-admin-openapi.sh --check`, `npm --prefix admin run typecheck`, `npm --prefix admin run test`, `npm --prefix admin run build`, `scripts/check-admin-dist.sh`, `TestCommandsDocumented|TestDocsTree`, and `summer docs:build --check`."
- "No git tag or push happens without explicit user approval at the decision checkpoint; after resolution, `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh` proves zero `pier` boot warnings, Journal + SEO + Sitemap scopes advertised with `plugin_id`/`group`, and multi-plugin write grants working locally (D-20)."
artifacts:
- path: "modules/pier/uncovered_scopes_warning_test.go"
provides: "Go unit tests for D-18 boot-time uncovered backend write MCP tool warnings using `captureLogs`"
contains: "TestUncoveredBackendWriteToolsWarning"
- path: "admin/tests/app/scopeCatalog.test.ts"
provides: "Pure unit tests for `scopeCatalog.ts` grouping, collision-safety, collation, search, expand, chips, serializer, initial states"
contains: "groupPluginScopes"
- path: "admin/tests/scopes/ScopeAccessControl.test.ts"
provides: "Vitest component tests for 3-tier selector, elevated-first chip cap=6 + `+N more`, empty/disabled/invalid states"
contains: "ScopeAccessControl"
- path: "admin/tests/scopes/ScopePicker.test.ts"
provides: "Vitest component tests for search, filter pills, `admin:read` lock + `via admin:read` badge, disabled `Read`, selective `Clear`, smart expand"
contains: "ScopePicker"
- path: "../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh"
provides: "Updated local E2E proof checking zero `pier` boot warnings, Journal + SEO + Sitemap scopes with `plugin_id`/`group`, and multi-plugin write grant"
contains: "sitemap"
key_links:
- from: "modules/pier/uncovered_scopes_warning_test.go"
to: "modules/pier/uncovered_scopes_warning.go"
via: "`pierAppWith` + `mountPier` + `captureLogs(t)` asserting structured `WARN` text output"
pattern: "captureLogs"
- from: "admin/tests/scopes/ScopePicker.test.ts"
to: "admin/src/components/scopes/ScopePicker.vue"
via: "Mounting `ScopePicker` with `setBundle` and exercising search, filter pills, `admin:read` toggle, and quick actions"
pattern: "data-via-admin-read"
- from: "../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh"
to: "modules/pier/uncovered_scopes_warning.go"
via: "Asserting `$TMP/go.log` has zero `not covered by any non-* TokenScope` warnings and `/gfadmin/api/v1/mcp/consent/$REQUEST_ID` returns Journal + SEO + Sitemap scopes with `plugin_id`/`group`"
pattern: "not covered by any non-\\* TokenScope"
prohibitions:
- "Do NOT run `git tag` or `git push` on `summercms.go`, `sm-sitemap-plugin`, `sm-seo-plugin`, or `sm-grzybyfunkcjonalne-app` until the user explicitly approves at Task 4's decision checkpoint (`CLAUDE.md`, D-20)."
- "Do NOT print, copy, or log plaintext tokens (including `~/.config/summercms/journal-token` or OAuth access/refresh tokens) in test failures or command output (`CLAUDE.md`, Phase 32.2 T-32.2-26)."
- "Do NOT deploy `grzybyfunkcjonalne.pl` to production (explicitly out of scope per D-20)."
---
<objective>
Close Phase 36 per `CLAUDE.md` rule 2 ("Unit tests are the last plan of every phase"): deliver full Go and Vitest unit/component test coverage (closing all 7 `backstop` rows from `36-UI-SPEC.md`), pass every framework release gate, pause for explicit user go-ahead before cutting dependency-ordered patch tags (`summercms.go` → `sm-sitemap-plugin` → `sm-seo-plugin`), and prove the complete Journal + SEO + Sitemap MCP OAuth flow locally in `../sm-grzybyfunkcjonalne-app` with zero `pier` boot warnings (D-20).
**Scope (Plan 36-04, Wave 4):** Go tests (`cabana`, `pier`), Vitest tests (`scopeCatalog`, `ScopeAccessControl`, `ScopePicker`, `ConnectView`, `connect.smoke`, `ApiTokenCreateDialog`, `ApiTokensPanel`), full framework release gates, release-tag decision checkpoint, and local `sm-grzybyfunkcjonalne-app` pointer bump + `scripts/smoke-mcp-oauth.sh` proof + changelog reminder.
</objective>
<execution_context>
@~/.claude/get-shit-done/workflows/execute-plan.md
@~/.claude/get-shit-done/templates/summary.md
</execution_context>
<context>
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-CONTEXT.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-UI-SPEC.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-RESEARCH.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-PATTERNS.md
@.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-VALIDATION.md
@CLAUDE.md
</context>
<threat_model>
## Trust Boundaries
| Boundary | Description |
|----------|-------------|
| Release tags (`v0.6.8` → plugin `v0.2.1` → consumer `go.mod` / submodules) | Published tags are immutable downstream contracts for every consuming SummerCMS app. |
| Embedded `modules/boardwalk/dist`, `admin/openapi/admin.json`, `schema.d.ts`, `docs/` → Go binary | Drift between source and committed build/OpenAPI artifacts would ship broken or outdated scope controls. |
| Test output & changelog script (`~/.config/summercms/journal-token`) → Console / CI logs | Secret token leakage in test failures or stdout compromises operator credentials. |
## STRIDE Threat Register
| Threat ID | Category | Component | Disposition | Mitigation Plan |
|-----------|----------|-----------|-------------|-----------------|
| T-36-09 | Supply Chain / Repudiation (HIGH) | Release tagging (`summercms.go`, `sm-sitemap-plugin`, `sm-seo-plugin`) & `scripts/smoke-mcp-oauth.sh` | mitigate | Enforce `autonomous: false` with a blocking `checkpoint:decision` (Task 4) before any `git tag`/`git push`; follow strict dependency tag order (`summercms.go` first, then `sm-sitemap-plugin`, then `sm-seo-plugin`, then `sm-grzybyfunkcjonalne-app` pointers); never echo or log bearer/API/`g15_` tokens in test failure output. |
| T-36-10 | Tampering / Drift | Release gates (`check-admin-openapi.sh`, `check-admin-dist.sh`, `docs:build --check`, `go test ./...`) | mitigate | Execute the entire framework verification suite (including Postgres `TestPhase10OpenAPIConformance`, `TestAccountTokens`, `TestMCPAdminConsent`, `check-admin-openapi.sh --check`, `check-admin-dist.sh`, and `docs:build --check`) before Task 4 so no drifted artifact can be tagged. |
</threat_model>
## Artifacts this phase produces
- **Extended Go test files:** `modules/cabana/token_scopes_test.go`, `modules/cabana/token_scope_names_test.go`, `modules/cabana/account_tokens_test.go`, `modules/cabana/mcp_admin_consent_test.go`
- **New Go test file:** `modules/pier/uncovered_scopes_warning_test.go`
- **New Vitest test files:** `admin/tests/app/scopeCatalog.test.ts`, `admin/tests/scopes/ScopeAccessControl.test.ts`, `admin/tests/scopes/ScopePicker.test.ts`
- **Extended Vitest test files:** `admin/tests/views/ConnectView.test.ts`, `admin/tests/smoke/connect.smoke.test.ts`, `admin/tests/account/ApiTokenCreateDialog.test.ts`, `admin/tests/account/ApiTokensPanel.test.ts`
- **Extended local E2E proof:** `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh` (plus approved pointer bumps in `../sm-sitemap-plugin/go.mod`, `../sm-seo-plugin/go.mod`, `../sm-grzybyfunkcjonalne-app/go.mod`, and submodules)
<tasks>
<task type="auto">
<name>Task 1: Add comprehensive Go unit & integration tests for `cabana` scope metadata, `TokenScopeCovers`, and `pier.Mount` boot warnings</name>
<files>modules/cabana/token_scopes_test.go, modules/cabana/token_scope_names_test.go, modules/cabana/account_tokens_test.go, modules/cabana/mcp_admin_consent_test.go, modules/pier/uncovered_scopes_warning_test.go</files>
<read_first>
- modules/cabana/token_scopes_test.go (lines 180-310)
- modules/cabana/token_scope_names_test.go (full file)
- modules/cabana/account_tokens_test.go (lines 90-140, 200-260)
- modules/cabana/mcp_admin_consent_test.go (lines 90-145)
- modules/pier/reaper_test.go (lines 1-50 — `captureLogs`)
- modules/pier/helpers_test.go (lines 225-295 — `pierAppWith`, `mountPier`)
- modules/pier/uncovered_scopes_warning.go
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-PATTERNS.md (Patterns 4–5)
</read_first>
<action>
Write thorough Go unit and integration tests covering SC-1, SC-2, D-01, D-14, D-15, D-16, and D-18:
1. **`modules/cabana/token_scopes_test.go`:**
- Add `TestTokenScopeGroupValidation`:
- Literal `Group: "Commerce"` compiles and passes `validateTokenScopeMessageKeys`.
- Valid `::` phrase key `Group: "acme.shop::lang.groups.sales"` passes when present in translator.
- Missing `::` phrase key `Group: "acme.shop::lang.groups.missing"` fails `validateTokenScopeMessageKeys` with error naming scope, plugin ID, and missing key (D-14, T-36-01).
- Empty `Group: ""` passes `validatePluginTokenScope` and `validateTokenScopeMessageKeys`.
- Add `TestScopeGroupFallbackResolution` covering all 5 D-16 cases:
- Explicit `TokenScope.Group` (literal and `::` phrase key) wins over `<pluginID>::lang.plugin.name` and permission `Tab`.
- Fallback 1: empty `Group` resolves `<pluginID>::lang.plugin.name` when present in phrasebook (in requested locale).
- Fallback 2: empty `Group` and no `lang.plugin.name` resolves unanimous non-empty `Tab` across matched `reg.permissions` (both literal `Tab` and `::`-translated `Tab`).
- Fallback 2 non-unanimous: when matched permissions have two distinct `Tab`s (or one has empty `Tab`), falls through to Fallback 3 (`PluginID`).
- Fallback 3: empty `Group`, no `lang.plugin.name`, no matched permissions → returns raw `PluginID`.
- Framework scopes (`*`, `admin:read`) and unknown stored scopes (`mapStoredScope`) always emit `PluginID: ""` and `Group: ""` (D-15, T-36-03).
2. **`modules/cabana/token_scope_names_test.go`:**
- Add `TestTokenScopeCovers` exercising:
- Both activated `cabana` guard path and raw `plugins []party.Plugin` path (and `party.Activated` fallback).
- Wildcard `*` alone returns `false` for `POST`/`PUT`/`DELETE` (non-`*` coverage required, T-36-02).
- `GET` and `HEAD` return `true` via `admin:read`.
- Single non-`*` scope covering method + all required permissions returns `true`.
- Read-only plugin scope (`GET`/`HEAD` only) returns `false` for `POST`.
- Multi-permission requirement split across two different scopes (neither covering all codes) returns `false`; one scope covering all codes returns `true`.
- Empty `permissions` slice on `POST` returns `false` (matching runtime `allowsUnderScope`).
- Covering scope declared by a second companion plugin returns `true`.
3. **`modules/cabana/account_tokens_test.go` & `modules/cabana/mcp_admin_consent_test.go`:**
- Assert raw JSON keys `"plugin_id"` and `"group"` are always present (even when `""` for `*`, `admin:read`, and unknown stored scopes) on `GET /account/tokens/scopes`, `GET /account/tokens`, and `GET /mcp/consent/{request}`, and carry resolved non-empty `plugin_id`/`group` on plugin scopes (D-15).
4. **`modules/pier/uncovered_scopes_warning_test.go` (new file in `package pier_test`):**
- Add `TestUncoveredBackendWriteToolsWarning` using `pierAppWith`, `mountPier`, and existing `captureLogs(t)` (`modules/pier/reaper_test.go:35`):
- Subtest `warns_once_per_plugin_for_uncovered_backend_writes`: plugin with 2 uncovered backend write tools (`POST`, `DELETE`) and 1 `GET` tool emits exactly ONE `WARN` log mentioning `plugin`, both sorted write tool names, and `pact.HasTokenScopes` (omitting the `GET` tool), and `pier.Mount` returns `nil` error (D-18).
- Subtest `silent_when_covered_by_token_scope`: plugin declaring `pact.HasTokenScopes` covering its write tool emits ZERO warnings.
- Subtest `silent_when_covered_by_companion_plugin_scope`: second plugin covering first plugin's write tool emits ZERO warnings.
- Subtest `warns_when_write_tool_has_empty_permissions`: backend `POST` tool with `Permissions: nil` triggers a warning (T-36-02).
- Subtest `skips_user_guarded_write_tools`: `user`-guarded `POST` MCP tool emits ZERO warnings.
</action>
<acceptance_criteria>
- `modules/pier/uncovered_scopes_warning_test.go` exists and tests all 5 subtests via `captureLogs(t)`.
- `go test -short ./modules/pact ./modules/cabana ./modules/pier -run 'TestTokenScope|TestScopeGroup|TestUncoveredBackendWriteToolsWarning' -count=1` executes all new tests and exits 0.
- `go vet ./... && go test -short ./modules/pact ./modules/cabana ./modules/pier ./modules/phrasebook` exits 0.
</acceptance_criteria>
<verify>
<automated>go vet ./... && go test -short ./modules/pact ./modules/cabana ./modules/pier ./modules/phrasebook -count=1</automated>
<fails_when>non-zero exit, compile error, or "FAIL" in output</fails_when>
</verify>
<done>All Go unit tests for `TokenScope.Group`, D-16 fallback, `AdminAPITokenScope`, `TokenScopeCovers`, and `pier.Mount` warnings pass cleanly.</done>
</task>
<task type="auto">
<name>Task 2: Add comprehensive Vitest unit & component tests closing all 7 `backstop` UI Considerations</name>
<files>admin/tests/app/scopeCatalog.test.ts, admin/tests/scopes/ScopeAccessControl.test.ts, admin/tests/scopes/ScopePicker.test.ts, admin/tests/views/ConnectView.test.ts, admin/tests/smoke/connect.smoke.test.ts, admin/tests/account/ApiTokenCreateDialog.test.ts, admin/tests/account/ApiTokensPanel.test.ts</files>
<read_first>
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-UI-SPEC.md (lines 593-628 — all 7 `backstop` rows)
- admin/src/app/scopeCatalog.ts
- admin/src/components/scopes/useScopeSelection.ts
- admin/src/components/scopes/ScopeAccessControl.vue
- admin/src/components/scopes/ScopePicker.vue
- admin/tests/app/dateFormat.test.ts (lines 1-60 — pure test pattern)
- admin/tests/form/PermissionEditorField.test.ts (lines 1-75 — standalone component mount + `setBundle` pattern)
- admin/tests/views/ConnectView.test.ts
- admin/tests/account/ApiTokenCreateDialog.test.ts
</read_first>
<action>
Write comprehensive Vitest unit and component tests covering every single `backstop` row from `36-UI-SPEC.md` lines 621–627:
1. **`admin/tests/app/scopeCatalog.test.ts` (new — backstops #1, #2, #4, #7):**
- `partitionCatalog`: splits `*`, `admin:read`, and plugin scopes preserving catalog order.
- `groupPluginScopes`: two plugins sharing the exact same translated `group` label (`"Blog"`) produce two distinct accordions keyed by `${plugin_id}\0${group}`, tie-broken by `plugin_id`; alphabetical collation respects locale (`'pl'` vs `'en'`); intra-group declared scope order is preserved (D-01, D-17).
- `matchesScopeQuery`: case-insensitive match across `name`, `label`, `description`, `plugin_id`, and resolved `groupLabel`.
- `computeDefaultExpanded`: small catalog (`<= 3` groups OR `<= 12` scopes) expands all; large catalog (`> 3` groups AND `> 12` scopes) expands only selected groups (none when empty); `searching = true` expands all matching groups (D-07).
- `buildSummaryModel`: `admin:read` (when ON) + write scopes sort ahead of `read_only` scopes; 8 selected scopes return `visible.length === 6` and `overflowCount === 2`; counts `selectedWriteCount`, `selectedPluginCount`, `distinctPluginCount` accurately (D-06).
- `computeSubmittedScopes`: `'custom'` with `adminRead: false` omits `admin:read` (T-36-04); `'custom'` with `adminRead: true` returns `['admin:read', ...selectedWriteScopes]` concisely while ignoring redundant `:read` codes.
- `resolveInitialState`: `'connect'` (defaults `read_only`; narrow plugin subset without `admin:read`/`*` → `custom` with subset selected; `*`-only → `full`) and `'token'` (defaults `read_only`; falls back to `full` when `admin:read` absent) (D-03, D-08).
2. **`admin/tests/scopes/ScopeAccessControl.test.ts` (new — backstop #7 + tier controls):**
- Renders 3-tier `RadioGroupRoot` (`full`, `read_only`, `custom`), omits missing tiers, hides `RadioGroupRoot` when `<= 1` tier available.
- In `custom` with 8 selected scopes (mix of `admin:read`, write, and read-only): verifies elevated-first chip order (`admin:read` → write → read-only), exact 6 visible `[data-summary-chip]` elements + clickable `[data-action="customize-scopes-more"]` showing `+2 more` that emits `customize` (D-06).
- In `custom` with 0 selected scopes: renders `scope_summary_empty` and `[data-action="customize-scopes"]`.
- Renders `aria-invalid="true"` and `border-danger` when `invalid` is true, and disables controls when `disabled` is true.
3. **`admin/tests/scopes/ScopePicker.test.ts` (new — backstops #2, #4):**
- Search matches plugin/group/label/code/description, auto-expands matching groups, restores pre-search expand state on Clear search (`[data-action="clear-scope-search"]`), and renders dashed empty search state with `:query` + **Clear search** when 0 matches.
- Filter pills (`All`, `Selected`, `Read-only`) show live counts across the full catalog and render specific empty states + **Show all scopes** when empty.
- Opt-in `admin:read` toggle (`[data-admin-read-checkbox]`):
- Unchecked by default in Custom (D-04, T-36-04).
- Checking it locks every `read_only` row checked + disabled with `[data-via-admin-read]` badge, disables per-group `Read` (`[data-group-action="read"]`), and makes per-group `Clear` (`[data-group-action="clear"]`) untick only unlocked write scopes (D-04, D-17).
- Unchecking it restores previously ticked `:read` scopes from `draftScopes` memory.
- Empty draft disables `[data-action="scope-picker-apply"]` and displays `scope_picker_none_selected`.
- Smart expand defaults hold for small (`<= 3` groups / `<= 12` scopes) vs large (`> 3` groups and `> 12` scopes) catalogs (D-07).
4. **Extend `admin/tests/views/ConnectView.test.ts` (backstops #1, #2, #3, #6):**
- Defaults: `Read-only (admin:read)` when grantable; narrow plugin-only subset opens in `Custom` with subset selected; `*`-only opens in `Full (*)`; hides `Custom` tier when only `*` and `admin:read` are grantable (D-03).
- Tier memory & auto-open empty Custom: clicking `Custom` when empty auto-opens `[data-scope-picker-dialog]`; clicking **Discard changes** / Escape reverts tier back to `Read-only` (D-09, D-11); applying a custom selection, switching to `Read-only`, then back to `Custom` restores the saved selection without reopening the modal.
- `admin:read` PII footgun fix end-to-end: picking `journal` without `admin:read` submits `['journal']` (never `admin:read`); enabling `admin:read` + `journal` submits `['admin:read', 'journal']` and displays `admin:read` chip first on the consent card (D-04, T-36-04).
- Light-surface & responsive modal classes: portaled `[data-dialog-overlay]` and `[data-scope-picker-dialog]` both carry `.connect-light-surface`, mobile full-screen sheet class `h-[100dvh]`, and desktop `sm:max-w-[640px]` and `sm:max-h-[85dvh]` (D-10, D-12).
5. **Extend `admin/tests/account/ApiTokenCreateDialog.test.ts` (backstops #1, #3, #5):**
- Defaults to `Read-only (admin:read)` when available, falling back to `Full (*)` when `admin:read` is absent (D-08).
- Clicking `Custom` (empty) or **Customize scopes…** swaps dialog view in place with ZERO second `[data-dialog-overlay]` (assert `document.body.querySelectorAll('[data-dialog-overlay]').length === 1`) and preserves fixed `max-w-[560px]` width (D-02, D-13).
- Pressing `Escape` inside the swapped `ScopePicker` view discards draft (reverting tier if auto-opened empty), returns to the token form without closing the dialog, and preserves typed `name` and selected `expires` (D-11, D-13).
- Pressing `mod+s` / `mod+enter` (or checking `[data-hotkey="mod+s mod+enter"]` absence) while in the swapped `ScopePicker` view does NOT submit the token creation request (T-36-06).
</action>
<acceptance_criteria>
- `admin/tests/app/scopeCatalog.test.ts`, `admin/tests/scopes/ScopeAccessControl.test.ts`, and `admin/tests/scopes/ScopePicker.test.ts` exist and pass.
- All 7 `backstop` UI Considerations from `36-UI-SPEC.md` have explicit passing Vitest assertions.
- `npm --prefix admin run typecheck && npm --prefix admin run test` exits 0 with zero failed tests across the entire admin SPA suite.
</acceptance_criteria>
<verify>
<automated>npm --prefix admin run typecheck && npm --prefix admin run test</automated>
<fails_when>non-zero exit, vue-tsc error, or Vitest assertion mismatch</fails_when>
</verify>
<done>All 7 `backstop` Vitest suites and existing admin SPA tests pass cleanly under `vue-tsc` and Vitest.</done>
</task>
<task type="auto">
<name>Task 3: Run full framework & sibling plugin release verification gates</name>
<files>admin/openapi/admin.json, admin/src/api/schema.d.ts, modules/boardwalk/dist/index.html</files>
<read_first>
- scripts/check-admin-openapi.sh
- scripts/check-admin-dist.sh
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-VALIDATION.md
- CLAUDE.md
</read_first>
<action>
Run the complete pre-release verification matrix across `summercms.go`, `../sm-sitemap-plugin`, and `../sm-seo-plugin` (T-36-10):
1. `go vet ./...`
2. `go test ./...` (full Go suite including Docker testcontainers Postgres tests: `TestAccountTokens`, `TestMCPAdminConsent`, `TestPhase10OpenAPIConformance`; if Docker socket permissions require it per `CLAUDE.md`, run via `sudo -u golem`).
3. `scripts/check-admin-openapi.sh --check`
4. `npm --prefix admin run typecheck && npm --prefix admin run test && npm --prefix admin run build && scripts/check-admin-dist.sh`
5. `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree' -count=1 && go run ./cmd/summer docs:build --check`
6. `(cd ../sm-sitemap-plugin && go vet ./... && go test -count=1 ./...) && (cd ../sm-seo-plugin && go vet ./... && go test -count=1 ./...)`
7. Confirm `git status` across `summercms.go`, `../sm-sitemap-plugin`, and `../sm-seo-plugin` shows clean staged/ready changes with no untracked temporary files or leaked secrets.
</action>
<acceptance_criteria>
- Full `go test ./...` (including Postgres integration & OpenAPI conformance) exits 0.
- `scripts/check-admin-openapi.sh --check` and `scripts/check-admin-dist.sh` both exit 0.
- `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree' -count=1` and `go run ./cmd/summer docs:build --check` both exit 0.
- Both sibling plugin suites (`../sm-sitemap-plugin`, `../sm-seo-plugin`) pass `go vet` and `go test`.
</acceptance_criteria>
<verify>
<automated>go vet ./... && go test ./... && scripts/check-admin-openapi.sh --check && npm --prefix admin run typecheck && npm --prefix admin run test && scripts/check-admin-dist.sh && go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree' -count=1 && go run ./cmd/summer docs:build --check && (cd ../sm-sitemap-plugin && go vet ./... && go test -count=1 ./...) && (cd ../sm-seo-plugin && go vet ./... && go test -count=1 ./...)</automated>
<fails_when>non-zero exit, OpenAPI drift, dist drift, docs error, or "FAIL" in output</fails_when>
</verify>
<done>Every framework and core-plugin verification gate is green and ready for release-tag decision.</done>
</task>
<task type="checkpoint:decision" gate="blocking">
<decision>Approve patch release tags (`summercms.go v0.6.8` → `sm-sitemap-plugin v0.2.1` → `sm-seo-plugin v0.2.1`), push, and `sm-grzybyfunkcjonalne-app` pointer bump — or run local-only proof first?</decision>
<context>
Per D-20 and `CLAUDE.md` ("Don't push, tag or deploy without the user's go-ahead"), all framework tests, Vitest suites, OpenAPI/dist/docs gates, and sibling plugin tests are now green. Cutting release tags is a **one-way** public step in dependency order:
1. Commit & push `summercms.go` + tag `v0.6.8`
2. Bump `summercms v0.6.8` in `../sm-sitemap-plugin/go.mod`, commit, push, tag `v0.2.1`
3. Bump `summercms v0.6.8` + `sm-sitemap-plugin v0.2.1` in `../sm-seo-plugin/go.mod`, commit, push, tag `v0.2.1`
4. Bump pointers (`go.mod` + submodules `plugins/golem15/{sitemap,seo}`) in `../sm-grzybyfunkcjonalne-app` and run `scripts/smoke-mcp-oauth.sh`
5. Publish changelog entries on `https://summercms.io/changelog` and `https://summercms.io/changelog/plugins` (`../sm-summercmsio-app/scripts/changelog-post.py`, per `CLAUDE.md`)
Production deployment of `grzybyfunkcjonalne.pl` remains out of scope for Phase 36 (D-20).
</context>
<options>
<option id="approve-release-and-proof">
<name>Approve patch tags, push, pointer bump, local E2E proof, and changelog posts</name>
<pros>Completes D-20 end-to-end in dependency order with published `v0.6.8` / `v0.2.1` tags and verified `sm-grzybyfunkcjonalne-app` pointers.</pros>
<cons>Publishes git tags immediately to remotes.</cons>
</option>
<option id="local-proof-only">
<name>Run local `sm-grzybyfunkcjonalne-app` E2E proof using local `replace` lines first; hold tagging/pushing until after manual browser UAT</name>
<pros>Lets you visually inspect `/connect` (light/dark + mobile `< 640px`) and `/account` in a real browser before cutting irreversible release tags.</pros>
<cons>Requires a short follow-up go-ahead to cut and push the three patch tags.</cons>
</option>
</options>
<resume-signal>Reply with `approve-release-and-proof` or `local-proof-only` (and any tag version adjustments if desired).</resume-signal>
</task>
<task type="auto">
<name>Task 5: Execute approved release/pointer step and run `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh` local E2E proof (D-20)</name>
<files>../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh, ../sm-grzybyfunkcjonalne-app/go.mod, ../sm-sitemap-plugin/go.mod, ../sm-seo-plugin/go.mod</files>
<read_first>
- ../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh (lines 170-439)
- ../sm-grzybyfunkcjonalne-app/go.work
- ../sm-grzybyfunkcjonalne-app/go.mod
- ../sm-sitemap-plugin/go.mod
- ../sm-seo-plugin/go.mod
- .planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-PATTERNS.md (Pattern 12)
- CLAUDE.md (lines 74-79 — changelog posting rules)
</read_first>
<action>
Follow the decision recorded at Task 4:
1. **If `approve-release-and-proof` was chosen:**
- Push `summercms.go` and tag `v0.6.8` (annotated tag, push tag).
- Update `../sm-sitemap-plugin/go.mod` to `require git.golem15.com/golem15/summercms v0.6.8`, run `go mod tidy` & `go test ./...`, commit, push, and tag `v0.2.1`.
- Update `../sm-seo-plugin/go.mod` to `require git.golem15.com/golem15/summercms v0.6.8` and `git.golem15.com/golem15/sm-sitemap-plugin v0.2.1`, run `go mod tidy` & `go test ./...`, commit, push, and tag `v0.2.1`.
- Update `../sm-grzybyfunkcjonalne-app` submodule pointers (`plugins/golem15/sitemap`, `plugins/golem15/seo`) and `go.mod` (`summercms v0.6.8`, `sm-sitemap-plugin v0.2.1`, `sm-seo-plugin v0.2.1`).
- Publish changelog notes per `CLAUDE.md` using `../sm-summercmsio-app/scripts/changelog-post.py` for `summercms.go v0.6.8`, `sm-sitemap-plugin v0.2.1` (`--repo ../sm-sitemap-plugin`), and `sm-seo-plugin v0.2.1` (`--repo ../sm-seo-plugin`), without ever printing or copying `~/.config/summercms/journal-token` (ask the user if the token file is missing/refused).
2. **If `local-proof-only` was chosen:**
- Do NOT run `git tag`, `git push`, or mutate git submodules (`plugins/golem15/seo`, `plugins/golem15/sitemap`) on any repo.
- Because `../sm-grzybyfunkcjonalne-app/go.work` pins `./plugins/golem15/seo` and `./plugins/golem15/sitemap` (the `v0.2.0` submodules), generate a temporary `GOWORK` file in `/tmp` (e.g. `TMP_GOWORK="$(mktemp /tmp/grzyby-go.XXXXXX.work)"` with `trap 'rm -f "$TMP_GOWORK"' EXIT`) copying `../sm-grzybyfunkcjonalne-app/go.work` using **absolute paths** (`APP_ROOT="$(cd ../sm-grzybyfunkcjonalne-app && pwd)"` and `PARENT="$(dirname "$APP_ROOT")"`) so every `use` entry resolves cleanly from `/tmp`, replacing `./plugins/golem15/seo` with `$PARENT/sm-seo-plugin`, `./plugins/golem15/sitemap` with `$PARENT/sm-sitemap-plugin`, and `../summercms.go` with `$PARENT/summercms.go`.
- Run `GOWORK="$TMP_GOWORK"` for the `go vet`, `go test`, and `scripts/smoke-mcp-oauth.sh` verification below (`smoke-mcp-oauth.sh` line 102's `go -C "$ROOT" build` inherits `GOWORK`), then delete `$TMP_GOWORK` so the submodules stay clean until release tags are approved.
3. **Extend & execute `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh` (both branches):**
- Extend Step 2 (`/.well-known/oauth-protected-resource/mcp`, line 288) to verify `scopes_supported` contains all of: `journal`, `journal:read`, `seo`, `seo:read`, `sitemap`, `sitemap:read`, `offline_access`.
- Update Step 6 (`GET /oauth/mcp/authorize`, line 332) from `--data-urlencode "scope=journal offline_access"` to `--data-urlencode "scope=admin:read journal seo sitemap offline_access"` so `cabana` offers `admin:read` plus Journal, SEO, and Sitemap on `GET /gfadmin/api/v1/mcp/consent/$REQUEST_ID` and permits granting `["journal", "seo", "sitemap"]` on `POST`.
- Extend Step 8 consent inspection (`GET /gfadmin/api/v1/mcp/consent/$REQUEST_ID`, lines 361–366) to assert:
- `journal`, `seo`, and `sitemap` are offered with non-empty `.plugin_id` and non-empty `.group`;
- `admin:read` is offered with `.plugin_id == ""` and `.group == ""` (and `*` likewise if present).
- Update Step 8 consent `POST` (line 368) to grant `{"decision":"allow","scopes":["journal","seo","sitemap"],"offline_access":true}` (without `*` and without `admin:read`).
- Extend Step 10 (OAuth `tools/list`, preserving Step 11's `g15_` PAT round which only holds `journal`) to assert write tools across all three plugins are visible without `*`: Journal (`journal_list_posts` + a write tool such as `journal_create_post`), SEO (`seo_set_url_seo` or equivalent declared write tool), and Sitemap (`sitemap_rebuild`).
- Assert `! grep -q 'not covered by any non-\* TokenScope' "$TMP/go.log"` so zero `pier` boot warnings are confirmed (D-18, D-20).
- Never print bearer tokens, refresh tokens, or `g15_` tokens in script output or error messages (T-36-09).
- Run `(cd ../sm-grzybyfunkcjonalne-app && go vet -tags summercms_mcp,nodynamic ./... && go test -short ./... && scripts/smoke-mcp-oauth.sh)` (prefixed with `GOWORK="$TMP_GOWORK"` under `local-proof-only`).
</action>
<acceptance_criteria>
- `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh` requests `scope=admin:read journal seo sitemap offline_access` in Step 6, checks `seo`, `seo:read`, `sitemap`, `sitemap:read`, `journal`, `journal:read` in Step 2, asserts non-empty `plugin_id`/`group` on `journal`/`seo`/`sitemap` and `""` on `admin:read` in Step 8 `GET`, grants `["journal", "seo", "sitemap"]` in Step 8 `POST`, asserts multi-plugin write tool visibility without `*` in Step 10 (keeping Step 11 `g15_` green), and asserts zero `not covered by any non-* TokenScope` warnings in `$TMP/go.log`.
- Under `approve-release-and-proof`, `(cd ../sm-grzybyfunkcjonalne-app && go vet -tags summercms_mcp,nodynamic ./... && go test -short ./... && scripts/smoke-mcp-oauth.sh)` exits 0; under `local-proof-only`, the same command with `GOWORK="$TMP_GOWORK"` exits 0 and leaves `../sm-grzybyfunkcjonalne-app` git submodules clean with `$TMP_GOWORK` deleted afterward.
- If `approve-release-and-proof` was chosen, tags `v0.6.8` (`summercms.go`), `v0.2.1` (`sm-sitemap-plugin`), and `v0.2.1` (`sm-seo-plugin`) exist in dependency order and changelog posts are published (or user notified if `~/.config/summercms/journal-token` is missing).
</acceptance_criteria>
<verify>
<automated>(cd ../sm-grzybyfunkcjonalne-app && go vet -tags summercms_mcp,nodynamic ./... && go test -short ./... && scripts/smoke-mcp-oauth.sh)</automated>
<fails_when>non-zero exit, uncovered-tool warning in go.log, missing SEO/Sitemap scope, or "FAIL" in output</fails_when>
</verify>
<done>Local `sm-grzybyfunkcjonalne-app` E2E proof passes with Journal + SEO + Sitemap scopes and zero `pier` boot warnings, honoring the user's Task 4 release decision.</done>
</task>
</tasks>
<verification>
Final Phase 36 sign-off checklist:
- `go vet ./... && go test ./...`
- `scripts/check-admin-openapi.sh --check`
- `npm --prefix admin run typecheck && npm --prefix admin run test && scripts/check-admin-dist.sh`
- `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree' -count=1 && go run ./cmd/summer docs:build --check`
- `(cd ../sm-sitemap-plugin && go vet ./... && go test -count=1 ./...) && (cd ../sm-seo-plugin && go vet ./... && go test -count=1 ./...)`
- `(cd ../sm-grzybyfunkcjonalne-app && go vet -tags summercms_mcp,nodynamic ./... && go test -short ./... && scripts/smoke-mcp-oauth.sh)`
</verification>
<success_criteria>
- All Go unit/integration tests and all Vitest unit/component tests (including all 7 `backstop` rows from `36-UI-SPEC.md`) pass green.
- Every framework release gate (OpenAPI, embedded `boardwalk/dist`, `TestDocsTree`, `docs:build --check`) passes green.
- Release tagging respects the blocking user decision checkpoint (`CLAUDE.md`, D-20), and `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh` proves zero boot warnings and full Journal + SEO + Sitemap granular scopes locally.
</success_criteria>
<output>
After completion, create `.planning/phases/36-granular-mcp-oauth-api-token-scope-picker/36-04-SUMMARY.md`
</output>

View File

@@ -0,0 +1,499 @@
# Phase 36: Granular MCP OAuth & API token scope picker - Pattern Map
**Mapped:** 2026-11-24
**Phase:** 36 - granular-mcp-oauth-api-token-scope-picker
**Sources verified:** `36-CONTEXT.md`, `36-UI-SPEC.md`, `36-RESEARCH.md`, `CLAUDE.md`, and direct reads of all cited source files across `summercms.go`, `sm-journal-plugin`, `sm-sitemap-plugin`, `sm-seo-plugin`, and `sm-grzybyfunkcjonalne-app`.
---
## 1. File Inventory & Classification
### A. Framework Go (`summercms.go`)
| File | Action | Role | Data Flow | Primary Analog(s) |
|------|--------|------|-----------|-------------------|
| `modules/pact/capabilities.go` | Modify | Capability contract (`TokenScope.Group`) | Plugin declaration → `cabana.compileTokenScopes` | `modules/pact/capabilities.go:851-877` (`Permission.Tab`, `TokenScope`) |
| `modules/cabana/token_scopes.go` | Modify | Scope catalog compilation & boot phrase-key validation | `[]party.Plugin` → `compiledTokenScope` → `validateTokenScopeMessageKeys` | `modules/cabana/token_scopes.go:22-30,89-99,160-176` |
| `modules/cabana/account_tokens.go` | Modify | Public admin API DTO (`AdminAPITokenScope`) & D-16 `group` fallback resolver | `compiledTokenScope` + `reg.permissions` + `phrasebook.Translator` → JSON (`plugin_id`, `group`) | `modules/cabana/account_tokens.go:13-20,171-187,264-308`; `modules/cabana/registry.go:235-236` |
| `modules/cabana/mcp_consent.go` | Modify | Consent show endpoint call site | `grantableConsentScopes` → `mapCompiledScope(ctx, tr, s.reg, scope)` → `MCPConsentView.Scopes` | `modules/cabana/mcp_consent.go:144-149` |
| `modules/cabana/token_scopes_export.go` | Modify | Exported coverage helper (`cabana.TokenScopeCovers`) | `app` / `plugins` → compiled `tokenScopeCatalog` → `scopeCoversAll` → `bool` | `modules/cabana/token_scopes_export.go:18-31`; `modules/cabana/token_resolver.go:76-111`; `modules/cabana/token_scopes.go:300-327` |
| `modules/pier/pier.go` | Modify | Boot hook (`Mount`) calling uncovered-write-tool warning check | `compileCatalog` → `warnUncoveredBackendWriteTools(app, plugins, cat)` → `logger().Warn` | `modules/pier/pier.go:109-119` |
| `modules/pier/uncovered_scopes_warning.go` *(or in `modules/pier/backend_guard.go`)* | Create / Modify | Boot-time structured warning for uncovered backend write MCP tools | `cat.tools` (`guardName == BackendGuard`, non-`GET`/`HEAD`) → `cabana.TokenScopeCovers` → 1 `Warn` per `pluginID` | `modules/pier/backend_guard.go:12,21`; `modules/pier/catalog.go:48-67`; `modules/pier/audit.go:19-22` |
| `modules/phrasebook/backend/lang/en/lang.yaml` | Modify | English admin UI copy (38 `api_tokens.*` incl. 3 CLDR plurals + 2 `mcp_connect.*`) | Embedded YAML → `GET /lang` → `t()` / `tc()` | `modules/phrasebook/backend/lang/en/lang.yaml:285-376,411-420` |
| `modules/phrasebook/backend/lang/pl/lang.yaml` | Modify | Polish admin UI copy (38 `api_tokens.*` incl. 3 CLDR `one/few/many/other` plurals + 2 `mcp_connect.*`) | Embedded YAML → `GET /lang` → `t()` / `tc()` | `modules/phrasebook/backend/lang/pl/lang.yaml:307-398,433-445` |
| `modules/pact/README.md`, `modules/cabana/README.md`, `modules/pier/README.md`, `docs/backend/users-and-permissions.md`, `docs/services/mcp.md` | Modify | Module API & docs contract (checked by `TestDocsTree` & `docs:build --check`) | Exported Go identifiers → docs checker | `modules/pact/README.md:113`; `modules/cabana/README.md:94-97,286-291`; `modules/pier/README.md:141`; `docs/backend/users-and-permissions.md:99`; `docs/services/mcp.md:115-137` |
| `modules/cabana/token_scopes_test.go` | Modify | Go unit tests: `TokenScope.Group`, missing phrase key, D-16 3-step fallback | `compileTokenCatalog` + `phrasebook.NewTranslator` → `mapCompiledScope` | `modules/cabana/token_scopes_test.go:198-290` |
| `modules/cabana/token_scope_names_test.go` | Modify | Go unit tests: `cabana.TokenScopeCovers` (activated guard, plugin slice, `GET`/`HEAD`, multi-perm, empty perms) | `backpack.App` / `[]party.Plugin` → `TokenScopeCovers` | `modules/cabana/token_scope_names_test.go:18-120` |
| `modules/cabana/account_tokens_test.go` | Modify | Integration test: `plugin_id` & `group` on `/account/tokens/scopes` and `/account/tokens` | HTTP JSON → `AdminAPITokenScope` | `modules/cabana/account_tokens_test.go:100-120,211-243` |
| `modules/cabana/mcp_admin_consent_test.go` | Modify | Integration test: `plugin_id` & `group` on `GET /mcp/consent/{request}` | HTTP JSON → `MCPConsentView.Scopes` | `modules/cabana/mcp_admin_consent_test.go:101-120` |
| `modules/pier/uncovered_scopes_warning_test.go` | Create | Go unit tests: D-18 boot warning log assertions | `pierAppWith` + `mountPier` + `captureLogs(t)` → `slog` text buffer | `modules/pier/reaper_test.go:17-44`; `modules/pier/helpers_test.go:232-285` |
### B. Generated Schema & Embedded Admin Build (`summercms.go`)
| File | Action | Role | Data Flow | Primary Analog(s) |
|------|--------|------|-----------|-------------------|
| `admin/openapi/admin.json` | Regenerate | OpenAPI 3.0 spec (`cabana.AdminAPITokenScope` gains required `plugin_id`, `group`) | `swag init --requiredByDefault` → `swagger2openapi` | `scripts/check-admin-openapi.sh:31-60` |
| `admin/src/api/schema.d.ts` | Regenerate | Generated TypeScript OpenAPI types consumed by `admin/src/api/types.ts:26` | `admin/openapi/admin.json` → `openapi-typescript` | `scripts/check-admin-openapi.sh:45`; `admin/src/api/types.ts:25-26,80` |
| `modules/boardwalk/dist/*` | Rebuild | Committed SPA bundle embedded in Go binary | `npm --prefix admin run build` → `scripts/check-admin-dist.sh` | `scripts/check-admin-dist.sh:1-26` |
### C. Admin SPA Source & Tests (`summercms.go/admin/`)
| File | Action | Role | Data Flow | Primary Analog(s) |
|------|--------|------|-----------|-------------------|
| `admin/src/styles/main.css` | Modify | Scoped light surface (`.connect-light-surface`) in `@layer components` | Re-declares `--c-*` + `--color-*` for `ConnectView` card & portaled `Dialog` | `admin/src/styles/main.css:24-48,83-132,189-219` |
| `admin/src/app/scopeCatalog.ts` | Create | Pure domain logic (partition, `(plugin_id, group)` group/sort, query match, effective select, smart expand, elevated-first chip model, serializer, initial state) | `readonly AdminAPITokenScope[]` → pure derived structs | `admin/src/components/form/control.ts:71-99`; `admin/src/app/i18n.ts:18,86-133` |
| `admin/src/components/scopes/useScopeSelection.ts` | Create | Reactive state composable (3-tier state, tier memory, auto-open empty Custom, draft clone, apply/discard with revert) | `Ref<AdminAPITokenScope[]>` + mode (`'connect' \| 'token'`) → reactive refs + actions | `admin/src/components/ui/confirm.ts:24-80` |
| `admin/src/components/scopes/ScopeAccessControl.vue` | Create | Shared 3-tier `RadioGroupRoot` + compact summary box (chips cap=6, `+N more`, subtitle, Customize button) | Props (`catalog`, `availableTiers`, `tier`, `custom`, `disabled`, `invalid`, `idPrefix`) ↔ emits (`update:tier`, `customize`) + `defineExpose({ focusPrimaryControl })` | `admin/src/components/account/ApiTokenCreateDialog.vue:433-454`; `admin/src/views/ConnectView.vue:485-538` |
| `admin/src/components/scopes/ScopePicker.vue` | Create | Shared sticky-header / scrollable `(plugin_id, group)` accordion / sticky-footer picker with `admin:read` toggle & `via admin:read` lock | Props (`catalog`, `draftAdminRead`, `draftScopes`, `cancelLabel`, `disabled`) ↔ emits (`update:draftAdminRead`, `update:draftScopes`, `apply`, `cancel`) + `defineExpose({ focusSearch })` | `admin/src/components/account/ApiTokenCreateDialog.vue:485-521`; `admin/src/components/form/control.ts:51-56` |
| `admin/src/views/ConnectView.vue` | Modify | Standalone `480px` MCP consent screen + responsive light-literal Customize modal (`100dvh` mobile / `max-w-[640px] max-h-[85dvh]` desktop) | `GET /mcp/consent/{request}` → `useScopeSelection(..., 'connect')` → `POST /mcp/consent/{request}` | `admin/src/views/ConnectView.vue:1-591`; `admin/src/components/account/ApiTokenCreateDialog.vue:352-396` (Reka `Dialog*`) |
| `admin/src/components/account/ApiTokenCreateDialog.vue` | Modify | 2-step personal token modal with in-dialog `ScopePicker` view swap (fixed `max-w-[560px]`, Escape = `← Back to token`) | `GET /account/tokens/scopes` → `useScopeSelection(..., 'token')` → `POST /account/tokens` | `admin/src/components/account/ApiTokenCreateDialog.vue:1-619` |
| `admin/src/components/account/ApiTokensPanel.vue` | Unchanged | Token list display (reads `name`, `label`, `known`; backwards-compatible with additive `plugin_id`/`group`) | `GET /account/tokens` → pill list | — |
| `admin/tests/fixtures/lang.json` | Modify | Polish test phrasebook fixture loaded by `resetState()` | Loaded in `admin/tests/helpers.ts:181` | `admin/tests/fixtures/lang.json:1-50` |
| `admin/tests/app/scopeCatalog.test.ts` | Create | Vitest pure unit tests for `scopeCatalog.ts` | Direct function assertions | `admin/tests/app/dateFormat.test.ts:1-80` |
| `admin/tests/scopes/ScopeAccessControl.test.ts` | Create | Vitest component tests for `ScopeAccessControl.vue` | `mount(ScopeAccessControl, ...)` + `setBundle` | `admin/tests/form/PermissionEditorField.test.ts:1-75` |
| `admin/tests/scopes/ScopePicker.test.ts` | Create | Vitest component tests for `ScopePicker.vue` | `mount(ScopePicker, ...)` + `setBundle` | `admin/tests/form/PermissionEditorField.test.ts:1-75` |
| `admin/tests/views/ConnectView.test.ts` | Modify | Vitest suite for `ConnectView.vue` (add `plugin_id`/`group` fixtures, update D-03 defaults, add modal/picker/draft tests) | `mountApp('/connect?request=req1', ...)` | `admin/tests/views/ConnectView.test.ts:1-120` |
| `admin/tests/smoke/connect.smoke.test.ts` | Modify | Smoke test for `/connect` (add `plugin_id`/`group`, update default allow to `['admin:read']`) | `mountApp('/connect?request=req1', ...)` | `admin/tests/smoke/connect.smoke.test.ts:12-86` |
| `admin/tests/account/ApiTokenCreateDialog.test.ts` | Modify | Vitest suite for `ApiTokenCreateDialog.vue` (add `plugin_id`/`group`, D-08 `Read-only` default, view swap, Escape, `mod+s`) | `mountApp('/account', ...)` | `admin/tests/account/ApiTokenCreateDialog.test.ts:15-120` |
| `admin/tests/account/ApiTokensPanel.test.ts` | Modify | Vitest suite for `ApiTokensPanel.vue` (add `plugin_id`/`group`, update dialog rules to 3-tier / Customize) | `mountApp('/account', ...)` | `admin/tests/account/ApiTokensPanel.test.ts:14-101` |
### D. Sibling Core Plugins & Local Proof Target
| File | Action | Role | Data Flow | Primary Analog(s) |
|------|--------|------|-----------|-------------------|
| `../sm-sitemap-plugin/token_scopes.go` | Create | `pact.HasTokenScopes` (`sitemap`, `sitemap:read`) | `Plugin.TokenScopes()` → `cabana` catalog & `pier` coverage | `../sm-journal-plugin/token_scopes.go:1-26` |
| `../sm-sitemap-plugin/lang/{en,pl}/lang.yaml` | Modify | EN/PL `scopes:` keys (`sitemap`, `sitemap_description`, `sitemap_read`, `sitemap_read_description`) | Embedded `langFS` → `phrasebook` | `../sm-journal-plugin/lang/en/lang.yaml:147-151`; `../sm-journal-plugin/lang/pl/lang.yaml:99-103` |
| `../sm-sitemap-plugin/token_scopes_test.go` | Create | Scope declaration, phrasebook YAML check, `TokenScopeCovers` / zero `pier.Mount` warning, read/write auth test | `Plugin.TokenScopes()` + `cabana` + `pier` | `../sm-journal-plugin/token_scopes_test.go:1-90` |
| `../sm-sitemap-plugin/README.md` | Modify | Document `TokenScopes` (`sitemap`, `sitemap:read`) | API reference | `../sm-sitemap-plugin/README.md:260-280` |
| `../sm-seo-plugin/token_scopes.go` | Create | `pact.HasTokenScopes` (`seo`, `seo:read`) | `Plugin.TokenScopes()` → `cabana` catalog & `pier` coverage | `../sm-journal-plugin/token_scopes.go:1-26` |
| `../sm-seo-plugin/lang/{en,pl}/lang.yaml` | Modify | EN/PL `scopes:` keys (`seo`, `seo_description`, `seo_read`, `seo_read_description`) | Embedded `langFS` → `phrasebook` | `../sm-journal-plugin/lang/en/lang.yaml:147-151`; `../sm-journal-plugin/lang/pl/lang.yaml:99-103` |
| `../sm-seo-plugin/token_scopes_test.go` | Create | Scope declaration, phrasebook YAML check, `TokenScopeCovers` across 26 write MCP tools / zero `pier.Mount` warning, read/write auth test | `Plugin.TokenScopes()` + `cabana` + `pier` | `../sm-journal-plugin/token_scopes_test.go:1-90` |
| `../sm-seo-plugin/README.md` | Modify | Document `TokenScopes` (`seo`, `seo:read`) | API reference | `../sm-seo-plugin/README.md:312-320` |
| `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh` | Modify | Local E2E proof (zero `pier:` warnings in `$TMP/go.log`, `seo`/`sitemap`/`journal` scopes + `plugin_id`/`group` on consent, multi-plugin write grant) | Built binary → live HTTP/MCP checks | `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh:249-360` |
| `../sm-sitemap-plugin/go.mod`, `../sm-seo-plugin/go.mod`, `../sm-grzybyfunkcjonalne-app/go.mod`, `../sm-grzybyfunkcjonalne-app/plugins/golem15/{sitemap,seo}` | Modify (release step) | Version bumps after user approval of patch tags (`summercms v0.6.8` → `sm-sitemap-plugin v0.2.1` → `sm-seo-plugin v0.2.1`) | Go module & submodule graph | `../sm-sitemap-plugin/go.mod:1-13`; `../sm-seo-plugin/go.mod:1-10` |
---
## 2. Verbatim Codebase Patterns by Area
### Pattern 1: `pact.TokenScope` & `Permission.Tab` (`modules/pact/capabilities.go:851-877`)
Add `Group string` to `pact.TokenScope`, mirroring `Permission.Tab` (optional literal or `::` phrase key):
```go
// Permission is one registerPermissions() entry.
type Permission struct {
Code string
Tab string
Label string
Roles []string
}
// TokenScope is one personal API token scope a plugin registers at boot.
// Label and Description are phrase keys (containing "::") or literal text.
type TokenScope struct {
Name string
Label string
Description string
Permissions []string
Methods []string
}
```
**Convention:** Keep `tokenScopeNameRE` (`modules/pact/capabilities.go:904`) and `ValidTokenScopeName` (`911-913`) untouched.
---
### Pattern 2: `cabana` Scope Compilation & Phrase-Key Validation (`modules/cabana/token_scopes.go:22-30, 89-99, 160-176`)
Carry `Group string` on `compiledTokenScope` (`strings.TrimSpace(scope.Group)`), and extend `validateTokenScopeMessageKeys` to check `scope.Group` alongside `Label` and `Description` (empty string has no `"::"`, so optional `Group` passes automatically):
```go
type compiledTokenScope struct {
Name string
Label string
Description string
Permissions []string
Methods map[string]bool
Full bool // framework scopes * and admin:read
PluginID string
}
```
```go
func validateTokenScopeMessageKeys(reg *Registry, tr *phrasebook.Translator) error {
if reg == nil || reg.tokenScopes == nil || tr == nil {
return nil
}
for _, scope := range reg.tokenScopes.ordered {
who := scope.PluginID
if who == "" {
who = "framework"
}
for _, text := range []string{scope.Label, scope.Description} {
if strings.Contains(text, "::") && !tr.Has(text) {
return fmt.Errorf("cabana: token scope %s (%s) names missing phrase key %s", scope.Name, who, text)
}
}
}
return nil
}
```
**Deterministic permission iteration** (`modules/cabana/registry.go:235-236`): `compilePermissionCatalog` always runs before `compileTokenScopes` (`registry.go:260-266`) and populates both `reg.permissions[code]` and `reg.permissionOrder = append(reg.permissionOrder, code)`. Iterate `reg.permissionOrder` for deterministic D-16 Fallback 2 (`Tab` unanimity check) using `scopeMatch(pattern, code) != matchNone` (`modules/cabana/token_scopes.go:179-235`).
---
### Pattern 3: `AdminAPITokenScope` DTO & Phrase Resolution (`modules/cabana/account_tokens.go:13-20, 264-308`)
Always-present JSON tags (no `omitempty`), matching existing fields so `swag init --requiredByDefault` generates required `string` properties in OpenAPI & TypeScript:
```go
// AdminAPITokenScope is one scope on a token or in the picker list.
type AdminAPITokenScope struct {
Name string `json:"name"`
Label string `json:"label"`
Description string `json:"description"`
ReadOnly bool `json:"read_only"`
Known bool `json:"known"`
}
```
```go
func mapStoredScope(ctx context.Context, tr *phrasebook.Translator, reg *Registry, name string) AdminAPITokenScope {
if reg != nil && reg.tokenScopes != nil {
if scope, ok := reg.tokenScopes.byName[name]; ok {
return mapCompiledScope(ctx, tr, scope)
}
}
return AdminAPITokenScope{Name: name, Label: name, Description: "", ReadOnly: false, Known: false}
}
func mapCompiledScope(ctx context.Context, tr *phrasebook.Translator, scope *compiledTokenScope) AdminAPITokenScope {
label := scope.Label
desc := scope.Description
if strings.Contains(label, "::") {
label = resolveScopePhrase(ctx, tr, label, label)
}
if strings.Contains(desc, "::") {
desc = resolveScopePhrase(ctx, tr, desc, desc)
}
// ...
}
func resolveScopePhrase(ctx context.Context, tr *phrasebook.Translator, key, fallback string) string {
if tr != nil && tr.Has(key) {
if s := tr.Get(ctx, key, nil); s != "" && s != key {
return s
}
}
return fallback
}
```
**All 3 call sites of `mapCompiledScope` to update to `(ctx, tr, reg, scope)`:**
- `modules/cabana/account_tokens.go:183` (`s.accountTokenScopes` — pass `s.reg`)
- `modules/cabana/account_tokens.go:267` (`mapStoredScope` — pass `reg`)
- `modules/cabana/mcp_consent.go:147` (`s.mcpConsentShow` — pass `s.reg`)
---
### Pattern 4: Exported `cabana` Catalog Lookup & Coverage Check (`modules/cabana/token_scopes_export.go:18-31`, `token_resolver.go:76-111`, `token_commands.go:101-109`, `token_scopes.go:300-327`)
`pier` already imports `cabana` (`modules/pier/backend_guard.go:12`). Because `pier` unit tests call `pier.Mount(host, app, plugins)` **without** `cabana.Activate` or `party.Activated` (`modules/pier/helpers_test.go:232-285`), `cabana.TokenScopeCovers(app, plugins, method, permissions)` should resolve the catalog in order: (1) `publishedResolverGuard(app).reg.tokenScopes`, (2) `compileTokenCatalog(plugins)` when `len(plugins) > 0`, (3) `tokenCatalogForApp(app)`:
```go
// modules/cabana/token_resolver.go:102-111
func publishedResolverGuard(app *backpack.App) *compositeGuard {
if app == nil {
return nil
}
res, ok := app.Lookup[*backendResolver]()
if !ok || res == nil || res.guard == nil {
return nil
}
return res.guard
}
```
```go
// modules/cabana/token_scopes.go:300-327
func scopeCoversAll(limit *bouncer.ScopeLimit, cover []string) bool {
if limit == nil || limit.Full {
return true
}
if len(cover) == 0 {
return false
}
for _, patterns := range limit.Scopes {
ok := true
for _, code := range cover {
matched := false
for _, pattern := range patterns {
if scopeMatch(pattern, code) != matchNone {
matched = true
break
}
}
if !matched {
ok = false
break
}
}
if ok {
return true
}
}
return false
}
```
**Coverage invariant:** `scopeCoversAll` returns `false` when `len(cover) == 0` and `!limit.Full`, matching `allowsUnderScope` (`token_scopes.go:250`) — so a backend write tool with empty `Permissions` is correctly reported as uncovered.
---
### Pattern 5: `pier.Mount` Warning Hook & Log Capture in Tests (`modules/pier/pier.go:109-119`, `audit.go:19-22`, `reaper_test.go:17-44`)
Hook right after `compileCatalog` succeeds (`modules/pier/pier.go:112-115`):
```go
cat, err := compileCatalog(host, reg, plugins)
if err != nil {
return err
}
warnUncoveredBackendWriteTools(app, plugins, cat)
```
Structured logger (`modules/pier/audit.go:20-22`):
```go
func logger() *slog.Logger {
return diary.For(LogComponent)
}
```
Log capture helper already in `package pier_test` (`modules/pier/reaper_test.go:35-44` — reusable directly from `modules/pier/uncovered_scopes_warning_test.go`):
```go
func captureLogs(t *testing.T) *logBuffer {
t.Helper()
buf := &logBuffer{}
previous := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{Level: slog.LevelDebug})))
t.Cleanup(func() { slog.SetDefault(previous) })
return buf
}
```
`pier` test harness (`modules/pier/helpers_test.go:232-285`): `pierAppWith(t, extra, guard)` + `mountPier(t, app, plugins)` mounts `pier` directly over `surf.BuildRouter(app, plugins)` with `mcp.enabled: true`. Note `tool` struct fields in `modules/pier/catalog.go:48-56`: `t.name`, `t.pluginID`, `t.decl.Permissions`, `t.method`, `t.guardName` (`BackendGuard = "backend"`).
---
### Pattern 6: Phrasebook CLDR Plurals (`modules/phrasebook/backend/lang/{en,pl}/lang.yaml`)
EN uses `one`/`other` (`en/lang.yaml:411-415`); PL uses `one`/`few`/`many`/`other` (`pl/lang.yaml:433-439`):
```yaml
# modules/phrasebook/backend/lang/en/lang.yaml:412-414
removed_elements:
one: ":count element was removed: :names"
other: ":count elements were removed: :names"
```
```yaml
# modules/phrasebook/backend/lang/pl/lang.yaml:434-438
removed_elements:
one: "Usunięto :count element: :names"
few: "Usunięto :count elementy: :names"
many: "Usunięto :count elementów: :names"
other: "Usunięto :count elementu: :names"
```
Consumed in Vue via `tc('backend::lang.api_tokens.scope_count', count)` (`admin/src/app/i18n.ts:127-133`), which automatically supplies `{ count, ...params }` to `interpolate()`.
---
### Pattern 7: Scoped Light Surface in Tailwind v4 (`admin/src/styles/main.css:24-48, 189-219`)
`@theme` defines `--color-*: var(--c-*)` on `:root` (`main.css:28-46`), while `.dark` overrides `--c-*` (`main.css:108-132`). Place `.connect-light-surface` inside `@layer components` (`main.css:189+`, never `<style scoped>` because Reka `DialogPortal` teleports to `document.body`) re-declaring **both** `--c-*` and `--color-*: var(--c-*)` (verbatim block in `36-UI-SPEC.md:163-203`). Apply `.connect-light-surface` to the consent card AND to `DialogOverlay` + `DialogContent` in `ConnectView.vue`.
---
### Pattern 8: Reka UI `Dialog*`, `RadioGroup*`, Focus & Escape Handling (`admin/src/components/account/ApiTokenCreateDialog.vue:303-396, 433-454`)
Segmented `RadioGroupRoot` pattern (reused for `ScopeAccessControl.vue` 3-tier selector):
```vue
<!-- admin/src/components/account/ApiTokenCreateDialog.vue:437-452 -->
<RadioGroupRoot
v-model="expires"
orientation="horizontal"
aria-labelledby="api-token-expires-label"
class="inline-flex flex-wrap gap-1 rounded-inner border border-border bg-subtle p-1"
>
<RadioGroupItem
v-for="option in EXPIRY_OPTIONS"
:key="option.value"
:value="option.value"
data-expiry-segment
class="inline-flex h-pager items-center rounded-tab px-4 text-[13px] whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-text data-[state=checked]:bg-surface data-[state=checked]:text-text data-[state=checked]:shadow-tab data-[state=checked]:text-[14px] data-[state=checked]:font-semibold"
>
{{ t(option.label) }}
</RadioGroupItem>
</RadioGroupRoot>
```
Reka `Dialog` Escape & focus hooks (`ApiTokenCreateDialog.vue:311-365`):
```ts
function onEscapeKey(event: Event): void {
if (busy.value) {
event.preventDefault()
return
}
if (step.value === 1 && pickerOpen.value) { // Phase 36 D-13
event.preventDefault()
void onPickerCancel()
return
}
if (step.value === 2) {
event.preventDefault()
void requestClose()
}
}
```
```vue
<DialogRoot :open="open" @update:open="onOpenChange">
<DialogPortal>
<DialogOverlay data-dialog-overlay class="fixed inset-0 z-40 bg-overlay" />
<DialogContent
data-token-dialog
data-dialog-content
aria-modal="true"
class="fixed top-1/2 left-1/2 z-50 flex max-h-[calc(100vh-32px)] w-[calc(100%-32px)] max-w-[560px] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-modal bg-surface text-text shadow-pop"
@open-auto-focus="onOpenAutoFocus"
@close-auto-focus="onCloseAutoFocus"
@pointer-down-outside="onPointerOutside"
@interact-outside="onPointerOutside"
@escape-key-down="onEscapeKey"
>
```
**Hotkey rule (`admin/src/components/ui/Button.vue:44,55`, `ApiTokenCreateDialog.vue:552-563`):** `Button` binds `:data-hotkey="hotkey"`. Keeping the **Create token** `<Button hotkey="mod+s mod+enter">` inside `v-if="step === 1 && !pickerOpen"` automatically deactivates `mod+s`/`mod+enter` while the swapped `ScopePicker` view is active.
**Input control styling (`admin/src/components/form/control.ts:51-56`):**
```ts
export function controlClass(invalid: boolean | undefined): string {
return [
'w-full rounded-control border bg-surface px-3.5 text-text transition-colors duration-150 ease-out',
invalid ? 'border-danger' : 'border-border-strong',
].join(' ')
}
```
Apply `:class="controlClass(false)" class="h-input pl-10 pr-10"` on the `ScopePicker` search input.
**Locale collation (`admin/src/app/i18n.ts:18`):** Import `currentLocale` (`Readonly<Ref<string>>`) from `admin/src/app/i18n.ts` and pass `currentLocale.value` into `groupPluginScopes(pluginScopes, locale, fallbackGroupLabel)`.
---
### Pattern 9: Composable & Pure Module Conventions (`admin/src/components/ui/confirm.ts:24-80`)
Local component-adjacent composables live beside their components (e.g. `admin/src/components/ui/confirm.ts` → `admin/src/components/scopes/useScopeSelection.ts`), export plain TypeScript interfaces + one `export function use...()` returning refs, computeds, and methods without side-effectful global singletons. Pure domain helpers live under `admin/src/app/` (`scopeCatalog.ts`, mirroring `dateFormat.ts`, `listQuery.ts`) and are tested directly in `admin/tests/app/`.
---
### Pattern 10: Admin Vitest Component & Integration Test Harness (`admin/tests/helpers.ts:175-189`, `admin/tests/form/PermissionEditorField.test.ts:43-52`, `admin/tests/views/ConnectView.test.ts:55-68`)
Component tests mount standalone with `attachTo: document.body`, `resetState()`, `setBundle({ ...langFixture.data, ...strings }, 'en')`, and `enableAutoUnmount(afterEach)`:
```ts
// admin/tests/form/PermissionEditorField.test.ts:43-52
beforeEach(() => {
resetState()
setBundle({ ...langFixture.data, ...strings }, 'en')
})
afterEach(() => {
document.body.innerHTML = ''
})
enableAutoUnmount(afterEach)
```
App-level tests (`ConnectView.test.ts`, `connect.smoke.test.ts`, `ApiTokenCreateDialog.test.ts`, `ApiTokensPanel.test.ts`) use `mountApp(path, routes, { attach: true })`, `requestsTo(calls, 'POST', url)`, and `flushPromises()`. Remember `AdminAPITokenScope` fixtures in all 4 existing test files must include `plugin_id: string` and `group: string` once `schema.d.ts` is regenerated!
---
### Pattern 11: Sibling Plugin `pact.HasTokenScopes` & Tests (`../sm-journal-plugin/token_scopes.go:1-26`, `lang/{en,pl}/lang.yaml`, `token_scopes_test.go:1-65`)
Exact template for `../sm-sitemap-plugin/token_scopes.go` and `../sm-seo-plugin/token_scopes.go`:
```go
// ../sm-journal-plugin/token_scopes.go:1-26
package journal
import "git.golem15.com/golem15/summercms/modules/pact"
var _ pact.HasTokenScopes = (*Plugin)(nil)
// TokenScopes registers personal API token scopes for the Journal plugin.
func (p *Plugin) TokenScopes() []pact.TokenScope {
all := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
return []pact.TokenScope{
{
Name: "journal",
Label: "golem15.journal::lang.scopes.journal",
Description: "golem15.journal::lang.scopes.journal_description",
Permissions: []string{"golem15.journal.*"},
Methods: all,
},
{
Name: "journal:read",
Label: "golem15.journal::lang.scopes.journal_read",
Description: "golem15.journal::lang.scopes.journal_read_description",
Permissions: []string{"golem15.journal.*"},
Methods: []string{"GET", "HEAD"},
},
}
}
```
Exact phrasebook YAML block (`../sm-journal-plugin/lang/en/lang.yaml:147-151` & `pl/lang.yaml:99-103`):
```yaml
scopes:
journal: Journal
journal_description: Create, edit, publish and delete posts as you, within your Journal permissions.
journal_read: Journal, read-only
journal_read_description: Read posts, including drafts you may see, without changing anything.
```
Both target plugins ALREADY have:
- `plugin.name` in `lang/{en,pl}/lang.yaml` (`"Sitemap"` / `"Mapy witryny"` and `"SEO"` / `"SEO"`), so D-16 Fallback 1 resolves `group` automatically without needing `TokenScope.Group`.
- `controllers/api/auth.go` calling `cabana.ResolveBackend(..., "golem15.sitemap.*")` / `cabana.ResolveBackend(..., "golem15.seo.*")` and `cabana.Allows(principal, []string{PermissionManage})`.
- Both plugins already implement `pact.HasLang` with `//go:embed lang` (`../sm-sitemap-plugin/admin.go:19-26,60` and `../sm-seo-plugin/plugin.go:32,39-40`), so new `scopes:` keys in `lang/{en,pl}/lang.yaml` load automatically at boot.
Unit test template (`../sm-journal-plugin/token_scopes_test.go:13-65`): asserts scope names, `Permissions`, `Methods`, and parses both `lang/en/lang.yaml` and `lang/pl/lang.yaml` with `github.com/goccy/go-yaml` to guarantee every phrase key exists — extend in `sm-sitemap-plugin` and `sm-seo-plugin` with `cabana.TokenScopeNames`, `cabana.TokenScopeCovers` / `pier.Mount` zero-warning check, and scoped principal read vs. write enforcement.
---
### Pattern 12: Local E2E Smoke Script (`../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh:178, 282-360`)
- Server logs go to `$TMP/go.log` (line 178) — assert `! grep -q 'not covered by any non-\* TokenScope' "$TMP/go.log"`.
- Step 2 (lines 284-291) checks `.scopes_supported | index($s)` on `GET /.well-known/oauth-protected-resource/mcp` — extend loop to `journal journal:read seo seo:read sitemap sitemap:read offline_access`.
- Step 6/8 (lines 328-360+) requests scopes and inspects `GET /gfadmin/api/v1/mcp/consent/$REQUEST_ID` — assert each returned plugin scope carries non-empty `.plugin_id` and `.group`, and allow `["journal", "seo", "sitemap"]` to confirm multi-plugin write tools (`seo_set_url_seo`, `sitemap_rebuild`, `journal_list_posts`) appear in `tools/list`.
---
## 3. Release & Verification Gates Summary
| Gate | Command | Enforces |
|------|---------|----------|
| Go fast unit loop | `go vet ./... && go test -short ./modules/pact ./modules/cabana ./modules/pier ./modules/phrasebook` | Compilation, `TokenScope.Group`, D-16 fallback, `TokenScopeCovers`, D-18 warning |
| Full Go suite | `go test ./...` | Postgres integration (`TestAccountTokens`, `TestMCPAdminConsent`, `TestPhase10OpenAPIConformance`) |
| OpenAPI drift | `scripts/check-admin-openapi.sh` then `--check` | `admin/openapi/admin.json` & `admin/src/api/schema.d.ts` match `cabana` structs |
| Admin SPA build & tests | `npm --prefix admin run typecheck && npm --prefix admin run test && npm --prefix admin run build && scripts/check-admin-dist.sh` | TypeScript strictness, Vitest suites, embedded `modules/boardwalk/dist` parity |
| Docs & README identifiers | `go test ./cmd/summer -run 'TestCommandsDocumented\|TestDocsTree' && go run ./cmd/summer docs:build --check` | Every Go identifier & `src=` snippet in READMEs and `docs/` |
| Sibling plugins | `(cd ../sm-sitemap-plugin && go vet ./... && go test ./...)` and `(cd ../sm-seo-plugin && go vet ./... && go test ./...)` | `HasTokenScopes`, phrase keys, zero `pier.Mount` warnings, scoped enforcement |
| Local E2E proof | `(cd ../sm-grzybyfunkcjonalne-app && scripts/smoke-mcp-oauth.sh)` | Zero boot warnings + Journal/SEO/Sitemap scopes over MCP OAuth |

View File

@@ -0,0 +1,620 @@
# Phase 36: Granular MCP OAuth & API token scope picker - Research
**Researched:** 2026-11-24
**Domain:** Go backend (`pact`, `cabana`, `pier`, `phrasebook`), Vue 3 / TypeScript Admin SPA (`admin/` + embedded `modules/boardwalk/dist`), sibling core plugins (`sm-seo-plugin`, `sm-sitemap-plugin`), and `sm-grzybyfunkcjonalne-app` local verification.
**Confidence:** HIGH — every struct field, signature, CSS token, test file, phrasebook key, and sibling plugin file cited below was read directly from source in this session.
<user_constraints>
## User Constraints (from 36-CONTEXT.md & approved 36-UI-SPEC.md)
### Locked Decisions
- **D-01:** Feature-level granularity is first-class; `pact.ValidTokenScopeName` (`^[a-z][a-z0-9_-]*(:[a-z][a-z0-9_-]*)?$`) stays unchanged.
- **D-02:** Option D layout: `ConnectView.vue` keeps its `480px` standalone card with 3-tier access selector (**Full `*`** | **Read-only `admin:read`** | **Custom**), compact summary box, and **Customize scopes…** button opening a dedicated modal; `ApiTokenCreateDialog.vue` reuses the exact same `ScopePicker` via an in-dialog view swap (`← Back to token` / `Apply scopes`, never a nested modal overlay).
- **D-03:** `/connect` defaults to `Read-only (admin:read)` when requested and grantable; narrow plugin subset without `admin:read`/`*` opens in `Custom` with those scopes selected; `*`-only opens in `Full (*)`; hide `Custom` tier when no plugin scopes are grantable. Preserve Phase 32.2 invariants (hidden ungrantable scopes, `offline_access` ticked by default, no auto-allow, no initial focus or hotkey on Allow/Deny).
- **D-04:** Inside Custom, opt-in unchecked-by-default toggle **"Also allow reading all other plugins (`admin:read`)"**. When ON: every `read_only` row is locked-checked with `via admin:read` badge (`Lock` icon + text), `admin:read` chip appears first on the summary card, submitted scopes become `['admin:read', ...selectedWriteScopes]`. When OFF: `admin:read` is omitted so unticking `:read` scopes genuinely blocks read access.
- **D-05:** `pact.HasTokenScopes` remains explicit (no auto-generation at boot).
- **D-06:** Custom summary box shows elevated-first chips (`admin:read` → write scopes → read-only scopes when `admin:read` is OFF), capped at 6 + clickable `+N more` chip + `"X scopes across Y plugins"` subtitle.
- **D-07:** Smart accordion expansion on picker open: `≤ 3` groups or `≤ 12` plugin scopes → expand all; larger catalog → expand only groups with active selections; while searching → auto-expand all matching groups without destroying pre-search expand state.
- **D-08:** `ApiTokenCreateDialog.vue` initializes on `Read-only (admin:read)` when available, falling back to `Full (*)`.
- **D-09:** Clicking `Custom` when empty auto-opens `ScopePicker` (recording `autoOpenedFrom`); switching away to `Read-only`/`Full` and back to `Custom` restores the saved custom selection in memory.
- **D-10:** `ConnectView.vue` Customize modal is a `100dvh` full-screen sheet on `< 640px` and `max-w-[640px] max-h-[85dvh]` centered modal on `≥ 640px`, with sticky header and footer.
- **D-11:** Draft-until-Apply semantics; Cancel / `X` / Escape / `← Back` discards draft and reverts tier if Custom was auto-opened empty.
- **D-12:** Surface-matched theming: `ScopeAccessControl` + `ScopePicker` use semantic Tailwind/CSS tokens; `ApiTokenCreateDialog` inherits light/dark mode automatically; `ConnectView` pins light-literal tokens via `.connect-light-surface` in `@layer components` in `admin/src/styles/main.css` (applied on both consent card and portaled Reka `DialogOverlay` + `DialogContent`).
- **D-13:** `ApiTokenCreateDialog` stays fixed at `max-w-[560px]` across all views; pressing Escape in the swapped `ScopePicker` view discards draft and returns to token form without closing the dialog or losing `name`/`expires`.
- **D-14:** Optional `Group string` on `pact.TokenScope` (phrase key containing `::` validated by `validateTokenScopeMessageKeys`, or literal text, mirroring `pact.Permission.Tab`).
- **D-15:** `cabana.AdminAPITokenScope` adds always-present `PluginID string` (`json:"plugin_id"`) and `Group string` (`json:"group"`) with no `omitempty`. Framework scopes (`*`, `admin:read`) and unknown stored scopes emit `plugin_id: ""` and `group: ""`.
- **D-16:** Fallback resolution order for `AdminAPITokenScope.group` when `TokenScope.Group` is empty (for non-framework plugin scopes):
1. `<pluginID>::lang.plugin.name` (if present and translated in phrasebook)
2. Matched `reg.permissions` `Tab` (if matched permissions resolve to a unanimous non-empty `Tab`, translated when containing `::`)
3. Raw `PluginID`
- **D-17:** Flat accordions keyed by `(plugin_id, group)` (`${plugin_id}\0${group}`), sorted alphabetically with `Intl.Collator(locale, { sensitivity: 'base' })` tie-breaking on `plugin_id`, preserving declared scope order within each group. When `admin:read` toggle is ON: disable per-group `Read`, and `Clear` unticks only unlocked (non-`read_only`) scopes.
- **D-18:** Boot-time uncovered backend write MCP tool warning in `pier.Mount`: check every compiled tool where `guardName == "backend"` and `method` is not `GET`/`HEAD` against all registered non-`*` `TokenScope`s by both HTTP method and permission coverage via a `cabana` helper. Group uncovered tools by `plugin_id`, emit one structured `Warn` log per plugin naming `plugin`, `tools`, and `pact.HasTokenScopes` guidance. Never break boot.
- **D-19:** Implement `pact.HasTokenScopes` in `sm-seo-plugin`, `sm-sitemap-plugin`, and any other core plugin discovered to have uncovered backend write MCP tools (`<name>:read` + `<name>` by default; granular split only where existing permissions separate distinct risk tiers).
- **D-20:** Cut patch release tags in dependency order (`summercms.go` `v0.6.8`, then updated core plugins), then local pointer bump & end-to-end verification in `sm-grzybyfunkcjonalne-app` (Journal + SEO + Sitemap scopes, zero boot warnings). Production deploy stays out of scope.
### Claude's Discretion
- Exact component decomposition under `admin/src/components/scopes/` (already detailed in approved `36-UI-SPEC.md`: `admin/src/app/scopeCatalog.ts`, `admin/src/components/scopes/useScopeSelection.ts`, `ScopeAccessControl.vue`, `ScopePicker.vue`).
- Exact exported `cabana` helper signature for `pier` coverage checks.
- Lean plan split (present suggested plan count before writing `PLAN.md` files; unit tests / Vitest + OpenAPI/dist checks as final plan per `CLAUDE.md`).
</user_constraints>
---
## Summary
Phase 36 spans four cleanly separable layers:
1. **Framework Go backend (`summercms.go`):**
- `modules/pact`: add `Group string` to `pact.TokenScope` (`modules/pact/capabilities.go:866-872`).
- `modules/cabana`: carry `Group` on `compiledTokenScope`, validate phrase keys in `validateTokenScopeMessageKeys`, add `PluginID` and `Group` (always-present, no `omitempty`) on `AdminAPITokenScope`, resolve `group` with the 3-step D-16 fallback in `mapCompiledScope(ctx, tr, reg, scope)`, and export a coverage helper (`cabana.TokenScopeCovers`) in `token_scopes_export.go` that reuses `scopeCoversAll` and handles both activated `cabana` registries and pre-activation / test plugin slices.
- `modules/pier`: call `warnUncoveredBackendWriteTools(app, plugins, cat)` in `pier.Mount` right after `compileCatalog` (`modules/pier/pier.go:112-115`), emitting one structured `logger().Warn(...)` per plugin with uncovered backend write tools without ever failing boot.
- `modules/phrasebook`: add all EN/PL `api_tokens.*` (including 3 CLDR plural keys) and `mcp_connect.*` copy specified verbatim in `36-UI-SPEC.md`, and update `modules/pact/README.md`, `modules/cabana/README.md`, `modules/pier/README.md`, `docs/backend/users-and-permissions.md`, and `docs/services/mcp.md`.
2. **Admin SPA (`admin/` + `modules/boardwalk/dist`):**
- Regenerate `admin/openapi/admin.json` and `admin/src/api/schema.d.ts` via `scripts/check-admin-openapi.sh`.
- Add `.connect-light-surface` inside `@layer components` in `admin/src/styles/main.css` (re-binding both `--c-*` and `--color-*` so Tailwind v4 `@theme` utilities stay light even under `<html class="dark">` and inside `DialogPortal`).
- Build the shared scope module (`scopeCatalog.ts`, `useScopeSelection.ts`, `ScopeAccessControl.vue`, `ScopePicker.vue`) and integrate it into `ConnectView.vue` (light-literal modal) and `ApiTokenCreateDialog.vue` (in-dialog view swap, fixed `max-w-[560px]`).
- Update existing admin test suites (`ConnectView.test.ts`, `connect.smoke.test.ts`, `ApiTokenCreateDialog.test.ts`, `ApiTokensPanel.test.ts`, `admin/tests/fixtures/lang.json`) and add unit tests for `scopeCatalog.ts`, `ScopeAccessControl.vue`, and `ScopePicker.vue`. Rebuild `modules/boardwalk/dist` and verify `scripts/check-admin-dist.sh`.
3. **Sibling Core Plugin Audit (Complete — 26 plugins audited):**
- **ONLY TWO core plugins have uncovered backend write MCP tools:**
- `sm-seo-plugin` (`golem15.seo`): 41 `backend`-guarded MCP tools (26 write + 15 GET), ALL guarded by single permission `golem15.seo.manage` and `tokenCover = "golem15.seo.*"`. **No `HasTokenScopes`.** → Add `seo` + `seo:read`.
- `sm-sitemap-plugin` (`golem15.sitemap`): 3 `backend`-guarded MCP tools (2 write + 1 GET), ALL guarded by single permission `golem15.sitemap.access_definitions` and `tokenCover = "golem15.sitemap.*"`. **No `HasTokenScopes`.** → Add `sitemap` + `sitemap:read`.
- `sm-journal-plugin` (`golem15.journal`): 11 `backend`-guarded MCP tools, **ALREADY implements `pact.HasTokenScopes`** (`journal`, `journal:read` covering `golem15.journal.*`).
- `sm-user-plugin` (`user_me`) and `sm-presentations-plugin` (deck/revision/image tools): use the **`user` guard** (frontend member tokens, not `backend` guard).
- All other 21 core plugins (`menu`, `faq`, `oauthserver`, `translate`, `feedback`, `golem`, `quizzes`, `quizzesgolem`, `chat`, `chatchannels`, `chatbots`, `chatvideo`, `forum`, `herald`, `userfriends`, `moderation`, `paymentgateway`, `pgstripe`, `paymentgatewaysubscriptions`, `sociallogin`, `mfa`) and `sm-grzybyfunkcjonalne-app/plugins/grzyby` do **not** implement `pact.HasMCP`.
4. **Release & Local Proof (`sm-grzybyfunkcjonalne-app`):**
- Tag `summercms.go` `v0.6.8` (currently on `v0.6.7`), then `sm-sitemap-plugin` `v0.2.1` (currently `v0.2.0`), then `sm-seo-plugin` `v0.2.1` (currently `v0.2.0`; requires `sm-sitemap-plugin`).
- Bump pointers in `sm-grzybyfunkcjonalne-app`, extend/run `scripts/smoke-mcp-oauth.sh` to verify Journal + SEO + Sitemap scopes in `scopes_supported` and `/gfadmin/api/v1/mcp/consent/{request}` (with `plugin_id`/`group`) and zero uncovered-tool warnings in `$TMP/go.log`.
---
## 1. Go Backend Findings (`pact`, `cabana`, `pier`, `phrasebook`, `docs`)
### 1.1 `modules/pact/capabilities.go`
[VERIFIED: modules/pact/capabilities.go:851-913]
Current structs and validator:
```go
// Permission is one registerPermissions() entry.
type Permission struct {
Code string
Tab string
Label string
Roles []string
}
// TokenScope is one personal API token scope a plugin registers at boot.
// Label and Description are phrase keys (containing "::") or literal text.
type TokenScope struct {
Name string
Label string
Description string
Permissions []string
Methods []string
}
// HasTokenScopes is implemented by plugins that declare personal API token scopes.
type HasTokenScopes interface {
TokenScopes() []TokenScope
}
var tokenScopeNameRE = regexp.MustCompile(`^[a-z][a-z0-9_-]*(:[a-z][a-z0-9_-]*)?$`)
```
**Planned change (D-14, D-01):**
- Add `Group string` to `pact.TokenScope` (zero value `""` triggers D-16 fallback resolution; non-empty literal or `::` phrase key mirrors `pact.Permission.Tab`).
- Update `TokenScope` doc comment to document `Group` (optional phrase key containing `::` or literal text).
- Keep `ValidTokenScopeName` and `tokenScopeNameRE` completely unchanged.
---
### 1.2 `modules/cabana/token_scopes.go`
[VERIFIED: modules/cabana/token_scopes.go:22-176, 178-395]
Current `compiledTokenScope` (lines 22–30):
```go
type compiledTokenScope struct {
Name string
Label string
Description string
Permissions []string
Methods map[string]bool
Full bool // framework scopes * and admin:read
PluginID string
}
```
Current `validateTokenScopeMessageKeys` (lines 160–176):
```go
func validateTokenScopeMessageKeys(reg *Registry, tr *phrasebook.Translator) error {
if reg == nil || reg.tokenScopes == nil || tr == nil {
return nil
}
for _, scope := range reg.tokenScopes.ordered {
who := scope.PluginID
if who == "" {
who = "framework"
}
for _, text := range []string{scope.Label, scope.Description} {
if strings.Contains(text, "::") && !tr.Has(text) {
return fmt.Errorf("cabana: token scope %s (%s) names missing phrase key %s", scope.Name, who, text)
}
}
}
return nil
}
```
Notice `compileTokenScopes` (`token_scopes.go:43-103`) runs AFTER `compilePermissionCatalog` (`registry.go:260-265` and `http.go:161`), so `reg.permissions` (`map[string]pact.Permission`) and `reg.permissionOrder` (`[]string`) are already populated when `compileTokenScopes` runs [VERIFIED: modules/cabana/registry.go:210-267; modules/cabana/http.go:160-189].
**Planned changes (D-14, D-16):**
1. Add `Group string` on `compiledTokenScope`, populated with `strings.TrimSpace(scope.Group)` in `compileTokenScopes` (lines 89–96). Framework scopes (`*`, `admin:read`) keep `PluginID: ""` and `Group: ""`.
2. In `validateTokenScopeMessageKeys`, extend the loop from `[]string{scope.Label, scope.Description}` to `[]string{scope.Label, scope.Description, scope.Group}` (ignoring empty strings; since `""` does not contain `"::"`, `strings.Contains(text, "::") && !tr.Has(text)` handles optional empty `Group` cleanly).
3. Verify `validatePluginTokenScope` (`token_scopes.go:105-158`): does NOT reject empty `scope.Group` (unlike `Label` and `Description` which are required).
---
### 1.3 `modules/cabana/account_tokens.go` & `modules/cabana/mcp_consent.go`
[VERIFIED: modules/cabana/account_tokens.go:13-20, 171-187, 264-308; modules/cabana/mcp_consent.go:144-149]
Current `AdminAPITokenScope` (`account_tokens.go:14-20`):
```go
type AdminAPITokenScope struct {
Name string `json:"name"`
Label string `json:"label"`
Description string `json:"description"`
ReadOnly bool `json:"read_only"`
Known bool `json:"known"`
}
```
All 3 callers of `mapCompiledScope`:
1. `account_tokens.go:183` (`s.accountTokenScopes` — has `s.reg`)
2. `account_tokens.go:267` (`mapStoredScope` — has `reg`)
3. `mcp_consent.go:147` (`s.mcpConsentShow` — has `s.reg`)
`AdminAPITokenScope` is the single schema referenced in `admin_openapi.go:430` (`MCPConsentView.Scopes`) and `admin_openapi.go:527` (`GET /account/tokens/scopes`) as well as `AdminAPIToken.Scopes` (`account_tokens.go:27`) [VERIFIED: modules/cabana/admin_openapi.go:430,527].
**Planned changes (D-15, D-16):**
1. Add always-present fields (no `omitempty`) to `AdminAPITokenScope`:
```go
type AdminAPITokenScope struct {
Name string `json:"name"`
Label string `json:"label"`
Description string `json:"description"`
ReadOnly bool `json:"read_only"`
Known bool `json:"known"`
PluginID string `json:"plugin_id"`
Group string `json:"group"`
}
```
- `mapStoredScope` (`account_tokens.go:270`) returns `AdminAPITokenScope{Name: name, Label: name, Description: "", ReadOnly: false, Known: false}` — `PluginID` and `Group` default to `""` and serialize as `"plugin_id": "", "group": ""`.
- Framework scopes (`scope.Full` / `scope.PluginID == ""`) emit `PluginID: ""` and `Group: ""`.
2. Update `mapCompiledScope(ctx context.Context, tr *phrasebook.Translator, reg *Registry, scope *compiledTokenScope) AdminAPITokenScope` and implement `resolveScopeGroup(ctx, tr, reg, scope) string` honoring exact D-16 precedence:
- If `scope.PluginID == ""` (framework scope): return `""`.
- If `scope.Group != ""`: if `strings.Contains(scope.Group, "::")`, return `resolveScopePhrase(ctx, tr, scope.Group, scope.Group)`; else return `scope.Group`.
- **Fallback 1:** `key := scope.PluginID + "::lang.plugin.name"`. If `tr != nil && tr.Has(key)`, let `s := strings.TrimSpace(tr.Get(ctx, key, nil))`. If `s != "" && s != key`, return `s`.
- **Fallback 2:** Unanimous non-empty `Tab` of matched `reg.permissions`:
- Iterate deterministically over `reg.permissionOrder` (or `reg.permissions` if `permissionOrder` empty).
- A registered permission `code` matches `scope` if any `pattern` in `scope.Permissions` satisfies `scopeMatch(pattern, code) != matchNone`.
- For each matched permission `p := reg.permissions[code]`:
- `rawTab := strings.TrimSpace(p.Tab)`
- If `rawTab == ""`: unanimous check fails (`return` fallback 3).
- Resolve `tab := rawTab`; if `strings.Contains(tab, "::")`, `tab = strings.TrimSpace(resolveScopePhrase(ctx, tr, tab, tab))`.
- If `tab == ""`: unanimous check fails.
- Compare against `firstTab`: if mismatch (`tab != firstTab`), unanimous check fails!
- If at least one permission matched and all resolved to the same non-empty `firstTab`, return `firstTab`.
- **Fallback 3:** Return `scope.PluginID`.
**Subtlety check on `reg.permissionOrder`:**
- `compilePermissionCatalog` (`modules/cabana/registry.go:235-236`) populates both `reg.permissions[code]` and `reg.permissionOrder = append(reg.permissionOrder, code)`. Iterating `reg.permissionOrder` is deterministic and covers every entry in `reg.permissions`.
- Note on `admin:token:scopes` CLI (`modules/cabana/token_commands.go:256-304`): it builds `map[string]any` (`name`, `label`, `read_only`, `full`, `permissions`) rather than `AdminAPITokenScope`. No breaking change required; existing `TestTokenCommands` (`modules/cabana/token_commands_test.go:210-228`) passes untouched.
---
### 1.4 `modules/cabana/token_scopes_export.go` & `modules/pier/pier.go` (D-18 Boot Warning)
[VERIFIED: modules/cabana/token_scopes_export.go:1-63; modules/cabana/token_resolver.go:76-111; modules/cabana/token_scopes.go:298-327; modules/cabana/contracts.go:331-347; modules/pier/pier.go:94-163; modules/pier/catalog.go:48-67; modules/pier/audit.go:20-22; modules/pier/backend_guard.go:12,21]
**Key architectural facts verified from source:**
1. **No circular dependency:** `modules/pier/backend_guard.go:12` already imports `git.golem15.com/golem15/summercms/modules/cabana`.
2. **Logger in `pier`:** `modules/pier/audit.go:20-22` defines `func logger() *slog.Logger { return diary.For(LogComponent) }` (`LogComponent = "pier"`). Tests capture it via `slog.SetDefault(...)` (`modules/pier/reaper_test.go:35-43`).
3. **Important test & boot-order nuance:**
- In production (`modules/surf/pier_on.go:23`), `pier.Mount(host, app, plugins)` runs with `plugins` passed in.
- In unit tests (`modules/pier/helpers_test.go:232-285`), `pierAppWith` + `mountPier` call `pier.Mount(host, app, plugins)` **WITHOUT activating `cabana` and WITHOUT publishing `party.Activated` on `app`!**
- Therefore, the exported `cabana` helper MUST accept `plugins []party.Plugin` (using `publishedResolverGuard(app)` when `cabana` is activated, else compiling from `plugins`, else falling back to `tokenCatalogForApp(app)`):
```go
// TokenScopeCovers reports whether at least one non-"*" token scope in the
// application's catalog allows method and covers every code in permissions.
// When cabana is activated on app, its compiled catalog is used; otherwise
// scopes are compiled from plugins (or party.Activated on app). Returns false
// when permissions is empty, when method is unsupported, or when no non-"*"
// scope covers every code.
func TokenScopeCovers(app *backpack.App, plugins []party.Plugin, method string, permissions []string) bool
```
Wait — to avoid compiling `compileTokenCatalog(plugins)` repeatedly inside a loop when `cabana` isn't activated (e.g., a plugin with 41 tools in a test without `cabana.Activate`), we can either:
- Export a batch helper OR a tiny `TokenScopeCoverage` / check slice, OR `cabana.UncoveredTokenScopes` / `cabana.TokenScopeCovers`:
- Actually, a clean, reusable exported helper in `modules/cabana/token_scopes_export.go`:
```go
// TokenScopeCovers reports whether at least one non-"*" personal API token
// scope allows method and covers every permission code in permissions.
// Uses the activated cabana catalog on app when available, else compiles
// from plugins (falling back to party.Activated). Never returns an error;
// a broken or missing catalog answers false for non-GET/HEAD methods.
func TokenScopeCovers(app *backpack.App, plugins []party.Plugin, method string, permissions []string) bool
```
AND if we want O(1) compilation even in non-cabana callers, `pier` only calls it when `t.guardName == BackendGuard && t.method != http.MethodGet && t.method != http.MethodHead`, OR we can export a small `type TokenScopeCheck struct { Method string; Permissions []string }` / `func TokenScopesCover(app *backpack.App, plugins []party.Plugin, checks []TokenScopeCheck) []bool` — OR even simpler: `TokenScopeCovers` is already O(1) whenever `cabana.Activate` ran (all real apps!), and compiling 10–30 plugins in a unit test takes <50µs. Keeping a single crystal-clear function signature `TokenScopeCovers(app *backpack.App, plugins []party.Plugin, method string, permissions []string) bool` is far easier to document in `modules/cabana/README.md` and test directly!
4. **Exact coverage semantics (matching runtime `cabana.Allows` + `allowsUnderScope`):**
- Look up `cat := tokenScopeCatalogFor(app, plugins)` (if `guard := publishedResolverGuard(app); guard != nil && guard.reg != nil && guard.reg.tokenScopes != nil` → use `guard.reg.tokenScopes`; else if `len(plugins) > 0` → `compileTokenCatalog(plugins)`; else `tokenCatalogForApp(app)`).
- If `cat == nil` (e.g. `compileTokenCatalog` returned an error): **do not fail boot**; handle gracefully! Note: in `pier`, if `compileTokenCatalog` returned an error (invalid plugin scope in an isolated test where `cabana` didn't run), returning `(covered bool, ok bool)` or skipping warnings on catalog compile error prevents bogus warnings — actually, if `TokenScopeCovers` returns `false` on compile error, wait: why would a valid test have a broken `HasTokenScopes`? Only tests specifically testing broken scopes in `cabana`. In `pier` tests, test plugins either don't implement `HasTokenScopes` (compiles cleanly with `*` and `admin:read` only!) or implement a valid `HasTokenScopes`.
- Normalize `method = strings.ToUpper(strings.TrimSpace(method))`.
- Collect `var scopes [][]string`:
- Loop `for _, scope := range cat.ordered`:
- `if scope.Name == scopeAll { continue }` (skip `*`)
- `if !scope.Methods[method] { continue }`
- `if scope.Full { return true }` (`admin:read` covers `GET`/`HEAD`!)
- `scopes = append(scopes, scope.Permissions)`
- Return `scopeCoversAll(&bouncer.ScopeLimit{Scopes: scopes}, permissions)`.
5. **Edge cases verified against `modules/cabana/token_scopes.go:246-327`:**
- **Empty `Permissions` (`len(t.decl.Permissions) == 0`):** At runtime, `allowsUnderScope` (`token_scopes.go:250`) returns `false` for empty `required` under ANY non-Full scope. `scopeCoversAll` (`token_scopes.go:304`) also returns `false` for empty `cover`. So a backend write tool with empty `Permissions` IS genuinely unreachable without `*`, and SHOULD trigger the warning!
- **`GET` / `HEAD`:** `pier` skips them (and `TokenScopeCovers` returns `true` via `admin:read`).
- **Non-backend guard (`t.guardName != BackendGuard`):** `pier` skips them (`user` guard uses member scopes, not `cabana` `TokenScope`s).
- **Multi-permission tool covered by two different scopes vs one scope:** At runtime (`TestAllowsScope`, `token_scopes_test.go:133`), ONE single scope must cover ALL required codes. `scopeCoversAll` enforces that exact rule!
- **Tool covered by another plugin's `TokenScope`:** Checking against all registered non-`*` scopes in the app avoids false positives when a companion plugin declares the covering scope.
- **Zero plugins / zero backend write tools:** `warnUncoveredBackendWriteTools` does nothing and emits zero logs.
- **Log format (D-18):**
- Group uncovered `t.name` (exposed tool name, e.g. `seo_create_redirect`) by `t.pluginID`, preserving first-seen plugin order and sorting tool names within each plugin.
- Emit ONE `logger().Warn(...)` per plugin:
```go
logger().Warn("pier: plugin registers backend write MCP tools not covered by any non-* TokenScope; implement pact.HasTokenScopes so scoped tokens and MCP OAuth grants can call them",
"plugin", pluginID,
"tools", tools,
)
```
- Call `warnUncoveredBackendWriteTools(app, plugins, cat)` in `pier.Mount` (`modules/pier/pier.go`) right after `compileCatalog` succeeds (line 115). Never return an error.
---
### 1.5 Phrasebook (`modules/phrasebook/backend/lang/{en,pl}/lang.yaml`) & Docs
[VERIFIED: modules/phrasebook/backend/lang/en/lang.yaml:285-376; modules/phrasebook/backend/lang/pl/lang.yaml:307-398; admin/src/app/i18n.ts:86-133]
- Existing `en/lang.yaml` has `api_tokens:` at lines 285–350 and `mcp_connect:` at lines 351–376.
- Existing `pl/lang.yaml` has `api_tokens:` at lines 307–372 and `mcp_connect:` at lines 373–398.
- CLDR plural YAML format is verified in `richeditor:` (`en/lang.yaml:411-420`, `pl/lang.yaml:433-440`):
- EN uses `one:` / `other:`
- PL uses `one:` / `few:` / `many:` / `other:`
- `admin/src/app/i18n.ts:127-133` evaluates `tc(key, count, params)` using `Intl.PluralRules(locale)` and passes `{ count, ...params }` to `interpolate()`.
- **All 38 new/updated keys under `api_tokens.*` (including 3 CLDR plural keys: `scope_count`, `scope_write_count`, `scope_plugin_count`) and 2 updated/new keys under `mcp_connect.*` (`subline`, `scope_picker_description`) are locked verbatim in `36-UI-SPEC.md` lines 251–304.**
- Also update `admin/tests/fixtures/lang.json` with the new Polish `backend::lang.api_tokens.*` and `backend::lang.mcp_connect.*` entries (since `admin/tests/helpers.ts:181` loads `langFixture.data` as `'pl'` in `resetState()`).
- **Required documentation updates per `CLAUDE.md`:**
1. `modules/pact/README.md` (line 113: add `Group` to `pact.TokenScope` row) [VERIFIED: modules/pact/README.md:113].
2. `modules/cabana/README.md` (lines 94, 96, 286–291: document `plugin_id`/`group` on `cabana.AdminAPITokenScope`, D-16 fallback, and `cabana.TokenScopeCovers`) [VERIFIED: modules/cabana/README.md:94-96,286-291].
3. `modules/pier/README.md` (line 141: document `pier.Mount` boot-time warning for uncovered backend write MCP tools) [VERIFIED: modules/pier/README.md:141].
4. `docs/backend/users-and-permissions.md` (line 99: add `Group` field and phrase-key validation note) [VERIFIED: docs/backend/users-and-permissions.md:99].
5. `docs/services/mcp.md` (add note under "Declaring tools and prompts" / "Identity and sessions" that backend write tools should be covered by `pact.HasTokenScopes` and `pier` warns at boot when uncovered) [VERIFIED: docs/services/mcp.md:115-137].
- Remember `CLAUDE.md` rule: every Go identifier mentioned in a module README or `docs/` page is checked by `go test ./cmd/summer -run TestDocsTree` and `go run ./cmd/summer docs:build --check`.
---
## 2. Admin SPA Findings (`admin/`)
### 2.1 Existing Files & Verified Mechanics
- **`admin/src/styles/main.css`** [VERIFIED: admin/src/styles/main.css:24-132, 189-531]:
- `:root` sets `--c-bg` through `--c-overlay` (lines 83–106).
- `.dark` overrides `--c-*` (lines 108–132).
- `@theme` maps `--color-bg: var(--c-bg)` through `--color-overlay: var(--c-overlay)` (lines 28–46).
- Because Tailwind v4 compiles `@theme` onto `:root`, overriding only `--c-*` on a descendant inside `<html class="dark">` does NOT re-evaluate `--color-*`. Defining `.connect-light-surface` inside `@layer components` with **both** `--c-*` light literals AND `--color-*: var(--c-*)` re-declarations (verbatim CSS in `36-UI-SPEC.md:163-203`) guarantees both `ConnectView`'s consent card and its `DialogPortal`-teleported Customize modal stay strictly light in dark mode.
- Note lines 7–9 of `main.css`: `@source not "../api/schema.d.ts"; @source not "../../openapi"; @source not "../../tests";` — generated OpenAPI types do not churn CSS.
- **`admin/src/api/types.ts`** [VERIFIED: admin/src/api/types.ts:26, 80]:
- `AdminAPITokenScope = Schemas['cabana.AdminAPITokenScope']` and `MCPConsent = Schemas['cabana.MCPConsentView']` are pure aliases onto `schema.d.ts`. Running `scripts/check-admin-openapi.sh` automatically updates `admin/openapi/admin.json` and `admin/src/api/schema.d.ts` with `plugin_id: string` and `group: string` (required, because `scripts/check-admin-openapi.sh:36` passes `--requiredByDefault` to `swag init`).
- **`admin/src/views/ConnectView.vue`** [VERIFIED: admin/src/views/ConnectView.vue:1-591]:
- Currently uses flat checkbox loop (`lines 487-522`), `checked = ref<Set<string>>`, `initialTicks` (ticks everything except `*`), and light-literal hex classes.
- Preserved Phase 32.2 invariants to keep untouched: 5 states (`loading`, `ready`, `expired`, `load_error`, `returning`), `logoUrl` same-origin/https check (`lines 65-78`), `safeDestination` + `FORBIDDEN_PROTOCOLS` + `returnsTo` (`lines 192-237`), `window.location.assign` (`line 274`), `switchAccount` calling `logout()` without router (`line 301`), focus management (`lines 312-334`), no auto-allow, no initial focus/hotkey on Allow/Deny.
- Notice `ConnectView.vue` currently has NO `reka-ui` imports — Phase 36 imports `DialogRoot`, `DialogPortal`, `DialogOverlay`, `DialogContent`, `DialogTitle`, `DialogDescription` from `reka-ui` (already installed `2.9.10` in `admin/package.json:33`) for the Customize modal.
- **`admin/src/components/account/ApiTokenCreateDialog.vue`** [VERIFIED: admin/src/components/account/ApiTokenCreateDialog.vue:1-619]:
- Already uses `reka-ui` `Dialog*` and `RadioGroup*`, fixed `max-w-[560px]` (`line 359`), Step 2 plaintext show-once (`lines 567-615`), `onEscapeKey` (`lines 331-340`), `mod+s mod+enter` hotkey on submit button (`line 557`).
- Phase 36 replaces the flat scope checkbox list (`lines 456-539`) with `ScopeAccessControl`, initializes on `Read-only (admin:read)` (fallback `Full (*)`, D-08), swaps the dialog interior to `ScopePicker` when `step === 1 && pickerOpen` (zero second overlay, `max-w-[560px]` unchanged), and intercepts `onEscapeKey` when `step === 1 && pickerOpen` (`event.preventDefault(); onPickerCancel()`, D-13).
- Subtlety: Check `onPointerOutside` (`lines 325-329`): when `step === 1 && pickerOpen`, should clicking outside the dialog close the whole dialog or be handled normally? Wait — in `ApiTokenCreateDialog`, `onOpenChange(false)` calls `requestClose()` which closes the dialog (resetting `pickerOpen = false` via `watch(() => props.open)`). That's clean and consistent with Reka `Dialog`. Meanwhile Escape inside `step === 1 && pickerOpen` strictly returns to the token form without closing the dialog (D-13).
- **`admin/src/components/account/ApiTokensPanel.vue`** [VERIFIED: admin/src/components/account/ApiTokensPanel.vue:265-285]:
- Reads only `scope.name`, `scope.label`, `scope.known`. Zero code changes needed!
### 2.2 Existing Admin Tests Impacted by Phase 36
Four existing Vitest files MUST be updated alongside the new unit tests:
1. **`admin/tests/views/ConnectView.test.ts`** [VERIFIED: lines 25-27, 74-84, 100-203, 221-249, 332-342]:
- Scope fixtures (`SCOPE_ALL`, `SCOPE_READ`, `SCOPE_ACME`) need `plugin_id` and `group` strings to pass `vue-tsc`.
- Old assertions expect flat `[data-scope]` checkboxes and initial ticks `['admin:read', 'acme']`. Under D-03, `consentView()` (with `[SCOPE_READ, SCOPE_ACME]`) now defaults to `Read-only (admin:read)` and posts `scopes: ['admin:read']`! Update assertions and add comprehensive tests for 3-tier defaults, narrow-subset `Custom`, `*`-only `Full`, hidden `Custom`, Customize modal light-surface/mobile classes, `admin:read` toggle & `via admin:read` lock, draft/discard revert.
2. **`admin/tests/smoke/connect.smoke.test.ts`** [VERIFIED: lines 17-20, 63-79]:
- Scope fixtures need `plugin_id` and `group`; default allow with `[admin:read, acme]` now posts `['admin:read']` (D-03).
3. **`admin/tests/account/ApiTokenCreateDialog.test.ts`** [VERIFIED: lines 19-51, 105-118, 210-256, 358-371, 471-493]:
- Scope fixtures need `plugin_id` and `group`.
- Old tests expected no preselected scope (submit disabled after load) and clicked flat `[data-scope="admin:read"] input`. Under D-08, `ApiTokenCreateDialog` now defaults to `Read-only (admin:read)` (so submit is enabled once scopes load!). Extend with in-dialog `ScopePicker` view swap, Escape returning to form preserving `name`/`expires`, zero second dialog overlay, and `mod+s` inactive inside picker view.
4. **`admin/tests/account/ApiTokensPanel.test.ts`** [VERIFIED: lines 14-101, 150-187, 358-475]:
- Scope fixtures need `plugin_id` and `group`.
- Its `dialog rules` tests (`lines 358-475`) click `[data-scope="*"] input` and `[data-scope="admin:read"] input` directly; update them to interact with `[data-access-tier="full"]` / default `read_only` / `[data-action="customize-scopes"]`.
5. **New unit test files (per `36-UI-SPEC.md` backstops):**
- `admin/tests/app/scopeCatalog.test.ts` (pure functions: `partitionCatalog`, `groupPluginScopes` collision safety & locale sort, `matchesScopeQuery`, `isEffectivelySelected`, `computeDefaultExpanded`, `buildSummaryModel` elevated-first cap=6 + `+N more`, `computeSubmittedScopes`, `resolveInitialState` for both `'connect'` and `'token'`).
- `admin/tests/scopes/ScopeAccessControl.test.ts` (tier switching, elevated-first chips + `+N more`, empty state, disabled/invalid states).
- `admin/tests/scopes/ScopePicker.test.ts` (search, clear search, filter pills with live counts, empty states, opt-in `admin:read` lock + `via admin:read` badge + disabling `Read` + `Clear` unticking only unlocked scopes, restoring prior `:read` ticks on toggle OFF, smart accordion expand defaults).
---
## 3. Sibling Core Plugins Audit (Complete Inventory)
Every core `sm-*-plugin` repository mounted across `sm-demo-app/summer.yaml`, `sm-grzybyfunkcjonalne-app/summer.yaml`, `sm-bm-app/summer.yaml`, `sm-summercmsio-app/summer.yaml`, and `fonoteka.go/summer.yaml` was audited via direct `read_file` of its `plugin.go` / `mcp.go` / `token_scopes.go`.
### 3.1 Full Audit Matrix (26 core plugins + 1 app plugin)
| Plugin repo | Plugin ID | `HasMCP`? | Guard | Backend write MCP tools? | `HasTokenScopes`? | Action in Phase 36 |
|-------------|-----------|-----------|-------|--------------------------|-------------------|--------------------|
| `sm-seo-plugin` | `golem15.seo` | **Yes** (`mcp.go:10`) | `backend` | **Yes (26 write + 15 GET = 41 tools)** | **NO** | **Add `HasTokenScopes` (`seo`, `seo:read`)** |
| `sm-sitemap-plugin` | `golem15.sitemap` | **Yes** (`mcp.go:10`) | `backend` | **Yes (2 write + 1 GET = 3 tools)** | **NO** | **Add `HasTokenScopes` (`sitemap`, `sitemap:read`)** |
| `sm-journal-plugin` | `golem15.journal` | **Yes** (`mcp.go:12`) | `backend` | Yes (6 write + 5 GET = 11 tools) | **Yes** (`token_scopes.go:5`: `journal`, `journal:read`) | None (already covered; reference implementation) |
| `sm-user-plugin` | `golem15.user` | Yes (`mcp.go:9`) | `user` | No (`GET`, `user` guard) | N/A | None |
| `sm-presentations-plugin` | `golem15.presentations` | Yes (`mcp.go:5`) | `user` (route middleware) | No (frontend member `user` guard) | N/A | None |
| `sm-menu-plugin` | `golem15.menu` | No | — | No | No | None |
| `sm-faq-plugin` | `golem15.faq` | No | — | No | No | None |
| `sm-oauthserver-plugin` | `golem15.oauthserver` | No | — | No | No | None |
| `sm-translate-plugin` | `golem15.translate` | No | — | No | No | None |
| `sm-feedback-plugin` | `golem15.feedback` | No | — | No | No | None |
| `sm-golem-plugin` | `golem15.golem` | No | — | No | No | None |
| `sm-quizzes-plugin` | `golem15.quizzes` | No | — | No | No | None |
| `sm-chat-plugin` | `golem15.chat` | No | — | No | No | None |
| `sm-chatchannels-plugin` | `golem15.chatchannels` | No | — | No | No | None |
| `sm-chatbots-plugin` | `golem15.chatbots` | No | — | No | No | None |
| `sm-chatvideo-plugin` | `golem15.chatvideo` | No | — | No | No | None |
| `sm-forum-plugin` | `golem15.forum` | No | — | No | No | None |
| `sm-herald-plugin` | `golem15.herald` | No | — | No | No | None |
| `sm-userfriends-plugin` | `golem15.userfriends` | No | — | No | No | None |
| `sm-moderation-plugin` | `golem15.moderation` | No | — | No | No | None |
| `sm-paymentgateway-plugin` | `golem15.paymentgateway` | No | — | No | No | None |
| `sm-pgstripe-plugin` | `golem15.pgstripe` | No | — | No | No | None |
| `sm-paymentgatewaysubscriptions-plugin` | `golem15.paymentgatewaysubscriptions` | No | — | No | No | None |
| `sm-sociallogin-plugin` | `golem15.sociallogin` | No | — | No | No | None |
| `sm-mfa-plugin` | `golem15.mfa` | No | — | No | No | None |
| `sm-grzybyfunkcjonalne-app/plugins/grzyby` | `golem15.grzyby` | No (commands only) | — | No | No | None |
Note: `sm-quizzesgolem-plugin` and `sm-summercmsio-plugin` were not present at top-level `../` paths (only referenced in other apps' `summer.yaml`); neither is used by `sm-grzybyfunkcjonalne-app` or `sm-demo-app`.
---
### 3.2 `sm-seo-plugin` Implementation Details
[VERIFIED: ../sm-seo-plugin/mcp.go:10-542; ../sm-seo-plugin/controllers/api/auth.go:19-96; ../sm-seo-plugin/lang/en/lang.yaml:1-20; ../sm-seo-plugin/lang/pl/lang.yaml:1-20; ../sm-seo-plugin/go.mod:1-20,182]
- **Module:** `git.golem15.com/golem15/sm-seo-plugin` (currently tagged `v0.2.0` in `sm-grzybyfunkcjonalne-app/go.mod:13`, requires `summercms v0.6.1` and `sm-sitemap-plugin v0.2.0`, has `replace git.golem15.com/golem15/summercms => ../summercms.go`).
- **Permissions:** Exactly ONE permission: `golem15.seo.manage` (`apicontrollers.PermissionManage`, `controllers.PermissionManage`).
- **Existing API token enforcement:** `controllers/api/auth.go:24,72` ALREADY calls `cabana.ResolveBackend(svc.App(), r, "golem15.seo.*")` and `cabana.Allows(principal, []string{PermissionManage})`.
- **Route methods on `/_seo/api/v1/*`:** `GET`, `POST`, `PUT`, `DELETE` (`routes.go:48-98`).
- **Existing plugin name key:** `golem15.seo::lang.plugin.name` = `"SEO"` (both EN and PL), so D-16 fallback 1 resolves `group` to `"SEO"` automatically (no explicit `Group` override needed, though omitting `Group` also keeps `sm-seo-plugin` compatible with older framework versions if desired — note D-20 bumps `summercms` first anyway!).
- **D-19 scope decision:** Because `sm-seo-plugin` has a single permission (`golem15.seo.manage`) rather than separate risk-tiered permissions, it gets the clean `<name>` + `<name>:read` pair (matching `sm-journal-plugin/token_scopes.go`):
- New file `token_scopes.go`:
```go
package seo
import "git.golem15.com/golem15/summercms/modules/pact"
var _ pact.HasTokenScopes = (*Plugin)(nil)
// TokenScopes registers personal API token scopes for the SEO plugin.
func (p *Plugin) TokenScopes() []pact.TokenScope {
all := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
return []pact.TokenScope{
{
Name: "seo",
Label: "golem15.seo::lang.scopes.seo",
Description: "golem15.seo::lang.scopes.seo_description",
Permissions: []string{"golem15.seo.*"},
Methods: all,
},
{
Name: "seo:read",
Label: "golem15.seo::lang.scopes.seo_read",
Description: "golem15.seo::lang.scopes.seo_read_description",
Permissions: []string{"golem15.seo.*"},
Methods: []string{"GET", "HEAD"},
},
}
}
```
- New phrasebook keys in `lang/en/lang.yaml` & `lang/pl/lang.yaml`:
- EN (`scopes:`):
- `seo: SEO`
- `seo_description: Manage SEO metadata, URL rules, redirects, robots.txt, pages, auto-links, settings and site audits as you, within your SEO permissions.`
- `seo_read: SEO, read-only`
- `seo_read_description: View SEO metadata, rules, redirects, 404 logs, robots.txt, settings, history and audit issues without making changes.`
- PL (`scopes:`):
- `seo: SEO`
- `seo_description: Zarządzaj metadanymi SEO, regułami adresów, przekierowaniami, robots.txt, stronami, automatycznymi linkami, ustawieniami i audytem witryny w ramach swoich uprawnień SEO.`
- `seo_read: SEO, tylko odczyt`
- `seo_read_description: Przeglądaj metadane SEO, reguły, przekierowania, dziennik 404, robots.txt, ustawienia, historię i problemy z audytu bez wprowadzania zmian.`
- Tests to add in `sm-seo-plugin`:
- Verify `cabana.TokenScopeNames` includes `"seo"` and `"seo:read"`.
- Verify `cabana.TokenScopeCovers` covers all 26 write MCP tools (and `pier.Mount` emits zero uncovered-tool warnings!).
- Verify a `g15_` token or scoped principal with `["seo"]` succeeds on `PUT /_seo/api/v1/seo` / `POST /_seo/api/v1/redirects` while `["seo:read"]` succeeds on `GET /_seo/api/v1/seo` and returns `403` on writes.
- Update `sm-seo-plugin/README.md` (`TokenScopes` in API reference).
---
### 3.3 `sm-sitemap-plugin` Implementation Details
[VERIFIED: ../sm-sitemap-plugin/mcp.go:10-55; ../sm-sitemap-plugin/controllers/api/auth.go:17-90; ../sm-sitemap-plugin/controllers/settings.go:29; ../sm-sitemap-plugin/lang/en/lang.yaml:1-5; ../sm-sitemap-plugin/lang/pl/lang.yaml:1-5; ../sm-sitemap-plugin/go.mod:1-13,177]
- **Module:** `git.golem15.com/golem15/sm-sitemap-plugin` (currently tagged `v0.2.0` in `sm-grzybyfunkcjonalne-app/go.mod:14`, requires `summercms v0.6.1`, has `replace git.golem15.com/golem15/summercms => ../summercms.go`).
- **Permissions:** Exactly ONE permission: `golem15.sitemap.access_definitions` (`controllers.PermissionAccessDefinitions`, `apicontrollers.PermissionManage`).
- **Existing API token enforcement:** `controllers/api/auth.go:22,70` ALREADY calls `cabana.ResolveBackend(a, r, "golem15.sitemap.*")` and `cabana.Allows(principal, []string{PermissionManage})`.
- **Route methods on `/_sitemap/api/v1/*`:** `GET /settings`, `PUT /settings`, `POST /rebuild` (`routes.go:60-65`).
- **Existing plugin name key:** `golem15.sitemap::lang.plugin.name` = `"Sitemap"` (EN) / `"Mapy witryny"` (PL), so D-16 fallback 1 resolves `group` automatically!
- **D-19 scope decision:** Clean `<name>` + `<name>:read` pair:
- New file `token_scopes.go`:
```go
package sitemap
import "git.golem15.com/golem15/summercms/modules/pact"
var _ pact.HasTokenScopes = (*Plugin)(nil)
// TokenScopes registers personal API token scopes for the Sitemap plugin.
func (p *Plugin) TokenScopes() []pact.TokenScope {
all := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
return []pact.TokenScope{
{
Name: "sitemap",
Label: "golem15.sitemap::lang.scopes.sitemap",
Description: "golem15.sitemap::lang.scopes.sitemap_description",
Permissions: []string{"golem15.sitemap.*"},
Methods: all,
},
{
Name: "sitemap:read",
Label: "golem15.sitemap::lang.scopes.sitemap_read",
Description: "golem15.sitemap::lang.scopes.sitemap_read_description",
Permissions: []string{"golem15.sitemap.*"},
Methods: []string{"GET", "HEAD"},
},
}
}
```
- New phrasebook keys in `lang/en/lang.yaml` & `lang/pl/lang.yaml`:
- EN (`scopes:`):
- `sitemap: Sitemaps`
- `sitemap_description: Read and update sitemap settings and trigger sitemap rebuilds as you, within your sitemap permissions.`
- `sitemap_read: Sitemaps, read-only`
- `sitemap_read_description: View sitemap settings, generated files, excluded addresses and IndexNow status without making changes.`
- PL (`scopes:`):
- `sitemap: Mapy witryny`
- `sitemap_description: Odczytuj i zmieniaj ustawienia map witryny oraz uruchamiaj ich odbudowę w ramach swoich uprawnień.`
- `sitemap_read: Mapy witryny, tylko odczyt`
- `sitemap_read_description: Przeglądaj ustawienia map witryny, wygenerowane pliki, pominięte adresy i stan IndexNow bez wprowadzania zmian.`
- Tests to add in `sm-sitemap-plugin`:
- Verify `cabana.TokenScopeNames` includes `"sitemap"` and `"sitemap:read"`.
- Verify `cabana.TokenScopeCovers` covers `sitemap_update_settings` and `sitemap_rebuild` (zero `pier.Mount` warnings).
- Verify a scoped principal with `["sitemap"]` succeeds on `PUT /_sitemap/api/v1/settings` and `POST /_sitemap/api/v1/rebuild`, while `["sitemap:read"]` succeeds on `GET` and gets `403` on writes.
- Update `sm-sitemap-plugin/README.md` (`TokenScopes` in API reference).
---
### 3.4 `sm-grzybyfunkcjonalne-app` Local Proof Setup (D-20)
[VERIFIED: ../sm-grzybyfunkcjonalne-app/summer.yaml; ../sm-grzybyfunkcjonalne-app/go.mod; ../sm-grzybyfunkcjonalne-app/go.work; ../sm-grzybyfunkcjonalne-app/.gitmodules; ../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh; ../sm-grzybyfunkcjonalne-app/scripts/build.sh]
- `summer.yaml` mounts `golem15.journal`, `golem15.seo`, `golem15.sitemap`, `golem15.menu`, `golem15.faq`, `golem15.oauthserver`, `golem15.user`, `golem15.translate`, `golem15.grzyby` with `build.tags: [summercms_mcp, nodynamic]`.
- `go.mod` pins `summercms v0.6.7`, `sm-seo-plugin v0.2.0`, `sm-sitemap-plugin v0.2.0` (with `replace` lines to `../summercms.go` and `./plugins/golem15/*` submodules).
- `scripts/smoke-mcp-oauth.sh` already runs a complete 12-step headless MCP OAuth flow on a throwaway Postgres DB (with Docker `postgres:15` or `SMOKE_ADMIN_DSN`) and writes Go server logs to `$TMP/go.log`!
- Extending/running `scripts/smoke-mcp-oauth.sh` after bumping pointers proves:
1. Zero `pier:` uncovered-tool `WARN` lines in `$TMP/go.log`.
2. `GET /.well-known/oauth-protected-resource/mcp` advertises `journal`, `journal:read`, `seo`, `seo:read`, `sitemap`, `sitemap:read`, `offline_access`.
3. `GET /gfadmin/api/v1/mcp/consent/{request}` returns `plugin_id` and resolved `group` on Journal, SEO, and Sitemap scopes.
4. Granting `["journal", "seo", "sitemap"]` (without `*`) lets MCP `tools/list` expose write tools across Journal, SEO (`seo_set_url_seo` etc.), and Sitemap (`sitemap_rebuild`).
- **Release ordering note (D-20 & `CLAUDE.md`):**
- Never push or tag without explicit user go-ahead (`CLAUDE.md:78`).
- When tagging:
1. `summercms.go` `v0.6.8` (after `check-admin-openapi.sh --check`, `check-admin-dist.sh`, `go test ./...`, `docs:build --check`)
2. `sm-sitemap-plugin` `v0.2.1` (bump `summercms` require to `v0.6.8` if needed, or keep `v0.6.8`)
3. `sm-seo-plugin` `v0.2.1` (bump `summercms` to `v0.6.8` and `sm-sitemap-plugin` to `v0.2.1`)
4. `sm-grzybyfunkcjonalne-app` submodule pointer bumps (`plugins/golem15/sitemap`, `plugins/golem15/seo`) + `go.mod` bumps (`summercms v0.6.8`, `sm-sitemap-plugin v0.2.1`, `sm-seo-plugin v0.2.1`).
- Minor note: `sm-grzybyfunkcjonalne-app/scripts/build.sh:19` currently lists `user translate journal sitemap menu faq oauthserver grzyby` in `PLUGINS=(...)` (omitting `seo`); keep `scripts/build.sh` untouched unless needed, or note for follow-up.
---
## 4. Common Pitfalls & Risks
1. **Tailwind v4 `@theme` dark-mode inheritance inside Reka `DialogPortal`:**
- Pitfall: Overriding only `--c-*` on `.connect-light-surface` leaves Tailwind utilities (`bg-surface`, `text-text`, `border-border`) reading the `:root`-resolved dark `--color-*` values.
- Prevention: Re-declare BOTH `--c-*` AND `--color-*: var(--c-*)` inside `.connect-light-surface` in `@layer components` in `admin/src/styles/main.css` (never Vue `<style scoped>`), and apply `.connect-light-surface` on both the consent card and the portaled `DialogOverlay` + `DialogContent`.
2. **`admin:read` toggle preserving pre-existing `:read` selections vs concise submitted scopes:**
- Pitfall: Turning `admin:read` ON and then OFF could accidentally wipe the user's earlier `:read` ticks, OR submitting `['admin:read', 'journal:read', 'journal']` when `admin:read` is ON would clutter the stored token.
- Prevention: Keep `custom.scopes` intact while `custom.adminRead === true`; in `computeSubmittedScopes`, when `custom.adminRead` is ON emit `['admin:read', ...selectedWriteScopes]`, and when OFF emit `selectedPluginScopes` (without `admin:read`).
3. **Empty `Permissions` on backend write MCP tools:**
- Pitfall: Treating `len(t.decl.Permissions) == 0` as "covered" in the `pier.Mount` warning would create a false negative — at runtime `allowsUnderScope` (`token_scopes.go:250`) refuses empty `required` for ALL non-Full scopes.
- Prevention: Rely on `scopeCoversAll` (`token_scopes.go:300-327`), which returns `false` for `len(cover) == 0` when `!limit.Full`.
4. **`pier.Mount` called in unit tests without `cabana.Activate` or `party.Activated`:**
- Pitfall: If `cabana.TokenScopeCovers` only reads `publishedResolverGuard(app)` or `party.Activated`, `pier` tests calling `pier.Mount(host, app, plugins)` directly will miss plugin scopes.
- Prevention: `TokenScopeCovers(app, plugins, method, permissions)` checks `publishedResolverGuard(app)` first, then compiles from `plugins` when non-empty, then falls back to `tokenCatalogForApp(app)`.
5. **Stale `admin/openapi/admin.json`, `admin/src/api/schema.d.ts`, or `modules/boardwalk/dist`:**
- Pitfall: Changing `AdminAPITokenScope` without running `scripts/check-admin-openapi.sh`, or changing `admin/src/` without `npm --prefix admin run build` and committing `modules/boardwalk/dist`, fails `TestPhase10OpenAPIConformance` and `scripts/check-admin-dist.sh`.
- Prevention: Run `scripts/check-admin-openapi.sh` immediately after Go backend changes, and `npm --prefix admin run build && scripts/check-admin-dist.sh` before finishing.
6. **Existing Vitest suites breaking due to D-03 / D-08 safe defaults & required `plugin_id`/`group`:**
- Pitfall: `ConnectView.test.ts`, `connect.smoke.test.ts`, `ApiTokenCreateDialog.test.ts`, and `ApiTokensPanel.test.ts` all assume the old flat checkboxes and old initial selections (`ApiTokenCreateDialog` previously started with 0 selected; `ConnectView` previously pre-ticked everything except `*`).
- Prevention: Plan explicit updates to all 4 existing test files plus `admin/tests/fixtures/lang.json`.
7. **CLDR plural interpolation in Polish (`scope_plugin_count`):**
- Pitfall: Polish locative after `"w"` uses `"1 wtyczce"`, `"2 wtyczkach"`, `"5 wtyczkach"`, `"1,5 wtyczki"` — verified verbatim in `36-UI-SPEC.md:261`. Do not substitute nominative `"wtyczka/wtyczki/wtyczek"`.
8. **Docs checker strictness (`TestDocsTree` / `summer docs:build --check`):**
- Pitfall: Mentioning a renamed or unexported Go identifier in `modules/*/README.md` or `docs/` fails `go test ./cmd/summer -run TestDocsTree`.
- Prevention: Run `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree'` and `go run ./cmd/summer docs:build --check` after editing READMEs/docs.
---
## 5. Validation Architecture
### Test Infrastructure & Tooling
- **Go:** `go 1.27.2` (standard `testing` package + `testcontainers-go v0.44.0` for Postgres integration tests; `-short` skips Docker).
- **Admin SPA:** `vitest 3.2.7` + `@vue/test-utils 2.4.11` + `happy-dom 20.11.6`, `vue-tsc 3.3.11`, `vite 7.3.5` (`node v24.22.0`, `npm 12.2.1`).
- **OpenAPI Gate:** `scripts/check-admin-openapi.sh --check` (`swag v1.16.6` → `internal/tools/swagger2openapi` → `openapi-typescript`).
- **Embedded SPA Gate:** `scripts/check-admin-dist.sh` (runs `npm --prefix admin run typecheck` + clean `vite build` diff against `modules/boardwalk/dist`).
- **Docs Gate:** `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree'` and `go run ./cmd/summer docs:build --check`.
- **Sibling Plugins:** `go vet ./...` and `go test -short ./...` / `go test ./...` inside `../sm-seo-plugin` and `../sm-sitemap-plugin`.
- **Local End-to-End Proof:** `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh`.
### Quick Feedback Commands (per-task)
```sh
# Go fast unit loop (no Docker)
go vet ./...
go test -short ./modules/pact ./modules/cabana ./modules/pier ./modules/phrasebook
# Admin SPA targeted unit loop
npm --prefix admin run typecheck
npm --prefix admin run test -- tests/app/scopeCatalog.test.ts tests/scopes/ tests/views/ConnectView.test.ts tests/smoke/connect.smoke.test.ts tests/account/ApiTokenCreateDialog.test.ts tests/account/ApiTokensPanel.test.ts
```
### Full Phase Verification Gate (before completion / release)
```sh
# 1. Go framework (vet + full suite incl. Postgres OpenAPI conformance)
go vet ./...
go test ./...
# 2. OpenAPI schema & generated TS types drift check
scripts/check-admin-openapi.sh --check
# 3. Admin SPA typecheck, full Vitest suite, embedded dist drift check
npm --prefix admin run typecheck
npm --prefix admin run test
npm --prefix admin run build
scripts/check-admin-dist.sh
# 4. Documentation & module README identifier/link check
go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree'
go run ./cmd/summer docs:build --check
# 5. Sibling core plugins (run from sibling directories)
(cd ../sm-sitemap-plugin && go vet ./... && go test ./...)
(cd ../sm-seo-plugin && go vet ./... && go test ./...)
# 6. Local end-to-end proof (sm-grzybyfunkcjonalne-app, needs Docker or SMOKE_ADMIN_DSN)
(cd ../sm-grzybyfunkcjonalne-app && go vet -tags summercms_mcp,nodynamic ./... && go test -short ./... && scripts/smoke-mcp-oauth.sh)
```
### Verification Map (Decisions & Success Criteria → Automated Checks)
| Target | Requirement / Decision | Automated Verification | Test File / Command |
|--------|------------------------|------------------------|---------------------|
| SC-1 / D-01, D-14, D-15, D-16 | `pact.TokenScope.Group`, `validateTokenScopeMessageKeys`, `AdminAPITokenScope` (`plugin_id`, `group` always-present), 3-step fallback resolution (`Group` → `::lang.plugin.name` → unanimous permission `Tab` → `PluginID`), framework/unknown empty strings | `go test -short ./modules/cabana -run 'TestTokenScope|TestScopeGroup'` + `go test ./modules/cabana -run 'TestPhase10OpenAPIConformance|TestAccountTokens|TestMCPAdminConsent'` + `scripts/check-admin-openapi.sh --check` | `modules/cabana/token_scopes_test.go`, `modules/cabana/account_tokens_test.go`, `modules/cabana/mcp_admin_consent_test.go`, `modules/cabana/openapi_conformance_test.go` |
| SC-2 / D-18 | `cabana.TokenScopeCovers` + `pier.Mount` boot warning per plugin for uncovered backend write MCP tools (GET/HEAD skipped, `user` guard skipped, empty `Permissions` warned, multi-permission single-scope rule, never breaks boot) | `go test -short ./modules/cabana -run TestTokenScopeCovers` + `go test -short ./modules/pier -run TestUncoveredBackendWriteToolsWarning` | `modules/cabana/token_scope_names_test.go` (or `token_scopes_test.go`), `modules/pier/uncovered_scopes_warning_test.go` (new) |
| SC-3 / D-02, D-03, D-04, D-06, D-07, D-09, D-10, D-11, D-12, D-17 | `ConnectView.vue` 3-tier defaults, elevated-first capped chips + `+N more`, Customize modal (`.connect-light-surface`, mobile `100dvh`, desktop `max-w-[640px] max-h-[85dvh]`), search/filter pills, flat `(plugin_id, group)` accordions, smart expand, `admin:read` toggle + `via admin:read` lock, draft/discard revert | `npm --prefix admin run test -- tests/app/scopeCatalog.test.ts tests/scopes/ tests/views/ConnectView.test.ts tests/smoke/connect.smoke.test.ts` | `admin/tests/app/scopeCatalog.test.ts` (new), `admin/tests/scopes/ScopeAccessControl.test.ts` (new), `admin/tests/scopes/ScopePicker.test.ts` (new), `admin/tests/views/ConnectView.test.ts`, `admin/tests/smoke/connect.smoke.test.ts` |
| SC-4 / D-02, D-08, D-11, D-12, D-13 | `ApiTokenCreateDialog.vue` `Read-only` default (fallback `Full`), shared `ScopePicker` in-dialog view swap (fixed `max-w-[560px]`, zero second dialog overlay), Escape returns to token form preserving `name`/`expires`, `mod+s` inactive in picker, semantic dark-mode tokens | `npm --prefix admin run test -- tests/account/ApiTokenCreateDialog.test.ts tests/account/ApiTokensPanel.test.ts` | `admin/tests/account/ApiTokenCreateDialog.test.ts`, `admin/tests/account/ApiTokensPanel.test.ts` |
| SC-5 | OpenAPI drift, embedded `modules/boardwalk/dist`, en/pl phrasebook completeness, module READMEs & docs checks | `scripts/check-admin-openapi.sh --check && scripts/check-admin-dist.sh && go test ./cmd/summer -run 'TestCommandsDocumented\|TestDocsTree' && go run ./cmd/summer docs:build --check` | `scripts/check-admin-openapi.sh`, `scripts/check-admin-dist.sh`, `cmd/summer` |
| D-19 | `sm-sitemap-plugin` (`sitemap`, `sitemap:read`) & `sm-seo-plugin` (`seo`, `seo:read`) implement `pact.HasTokenScopes` with en/pl copy, covering all backend write MCP tools | `(cd ../sm-sitemap-plugin && go vet ./... && go test ./...)` and `(cd ../sm-seo-plugin && go vet ./... && go test ./...)` | `../sm-sitemap-plugin/token_scopes_test.go` (new), `../sm-seo-plugin/token_scopes_test.go` (new) |
| D-20 | Local proof in `sm-grzybyfunkcjonalne-app`: zero boot warnings, Journal + SEO + Sitemap scopes advertised and grantable over MCP OAuth | `(cd ../sm-grzybyfunkcjonalne-app && scripts/smoke-mcp-oauth.sh)` | `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh` |
### Wave 0 Gaps (New Test Files to Create in Implementation / Final Test Plan)
- `modules/pier/uncovered_scopes_warning_test.go` — unit tests for D-18 boot warning (using `captureLogs` from `modules/pier/reaper_test.go:35`).
- `admin/tests/app/scopeCatalog.test.ts` — pure logic tests for grouping, collision safety, collation, query matching, smart expand, chip builder, submitted scopes, initial state resolver.
- `admin/tests/scopes/ScopeAccessControl.test.ts` — component tests for 3-tier radio control, elevated-first chip cap=6 + `+N more`, empty state, disabled/invalid states.
- `admin/tests/scopes/ScopePicker.test.ts` — component tests for search, filter pills, `admin:read` toggle & lock (`via admin:read`, disabled `Read`, selective `Clear`), smart expand, draft/apply/discard.
- `../sm-sitemap-plugin/token_scopes_test.go` & `../sm-seo-plugin/token_scopes_test.go` — plugin scope registration, `pier.Mount` zero-warning check, and scoped token write/read enforcement tests.
### Suggested Lean Plan Split (for Planner Reference)
Per `CLAUDE.md` lean-planning rules (few, large plans; unit tests as final plan):
1. **Plan 36-01 (`summercms.go` Go backend + OpenAPI + Phrasebook + Docs):** `pact.TokenScope.Group`, `cabana` group resolution + `AdminAPITokenScope` (`plugin_id`, `group`) + `TokenScopeCovers`, `pier.Mount` boot warning, en/pl phrasebook copy, `scripts/check-admin-openapi.sh`, module READMEs & `docs/`.
2. **Plan 36-02 (`summercms.go` Admin SPA + Embedded Dist):** `.connect-light-surface` in `main.css`, shared `scopeCatalog.ts` / `useScopeSelection.ts` / `ScopeAccessControl.vue` / `ScopePicker.vue`, `ConnectView.vue` + `ApiTokenCreateDialog.vue` integrations, `npm --prefix admin run build`, commit `modules/boardwalk/dist`.
3. **Plan 36-03 (Core Plugins `sm-sitemap-plugin` & `sm-seo-plugin`):** Add `pact.HasTokenScopes` (`sitemap`/`sitemap:read` and `seo`/`seo:read`), en/pl phrasebooks, README updates, and plugin tests.
4. **Plan 36-04 (Unit Tests, Release Gates & Local Proof):** Full Go unit tests (`cabana`, `pier`), full Vitest unit & component suites (`scopeCatalog`, `ScopeAccessControl`, `ScopePicker`, updated `ConnectView`, `connect.smoke`, `ApiTokenCreateDialog`, `ApiTokensPanel`, `lang.json`), all release gates (`go test ./...`, `check-admin-openapi.sh --check`, `check-admin-dist.sh`, `docs:build --check`), and `sm-grzybyfunkcjonalne-app` local `smoke-mcp-oauth.sh` proof (with user checkpoint before any git tag/push).
---
*Research completed: 2026-11-24*
*Ready for planning: yes*

View File

@@ -0,0 +1,85 @@
---
phase: "36"
slug: "granular-mcp-oauth-api-token-scope-picker"
status: draft
nyquist_compliant: false
wave_0_complete: false
created: "2026-11-24"
---
# Phase 36 — Validation Strategy
> Per-phase validation contract for feedback sampling during execution.
---
## Test Infrastructure
| Property | Value |
|----------|-------|
| **Framework** | Go `testing` (`go 1.27.2`) + `testcontainers-go` (Postgres) · Vitest `3.2.7` + `@vue/test-utils 2.4.11` + `happy-dom 20.11.6` + `vue-tsc 3.3.11` |
| **Config file** | `go.mod` · `admin/vitest.config.ts` (existing) |
| **Quick run command** | `go vet ./... && go test -short ./modules/pact ./modules/cabana ./modules/pier ./modules/phrasebook && npm --prefix admin run typecheck && npm --prefix admin run test` |
| **Full suite command** | `go vet ./... && go test ./... && scripts/check-admin-openapi.sh --check && npm --prefix admin run typecheck && npm --prefix admin run test && npm --prefix admin run build && scripts/check-admin-dist.sh && go test ./cmd/summer -run 'TestCommandsDocumented\|TestDocsTree' && go run ./cmd/summer docs:build --check` |
| **Estimated runtime** | ~25 seconds (quick) · ~90 seconds (full with Docker Postgres) |
---
## Sampling Rate
- **After every task commit:** Run targeted quick command (`go test -short` for Go packages or `npm --prefix admin run typecheck && npm --prefix admin run test -- <affected>` for SPA)
- **After every plan wave:** Run full Go short suite + Admin SPA typecheck/test + relevant gate script (`check-admin-openapi.sh --check` / `check-admin-dist.sh`)
- **Before `/msd-verify-work`:** Full suite must be green across `summercms.go`, `../sm-sitemap-plugin`, `../sm-seo-plugin`, and `../sm-grzybyfunkcjonalne-app` local smoke proof
- **Max feedback latency:** 30 seconds (quick loop)
---
## Per-Task Verification Map
*(Populated to task-level granularity when PLAN.md files are finalized; mapped to decisions and success criteria below.)*
| Target | Plan | Wave | Requirement / Decision | Threat Ref | Secure Behavior | Test Type | Automated Command | File Exists | Status |
|--------|------|------|------------------------|------------|-----------------|-----------|-------------------|-------------|--------|
| SC-1 | 01 | 1 | D-01, D-14, D-15, D-16 | T-36-01, T-36-03 | `pact.TokenScope.Group` validated when containing `::`; `AdminAPITokenScope` emits always-present `plugin_id` & `group` (`""` for framework/unknown); 3-step fallback preserves least-privilege scope semantics | unit + openapi | `go test -short ./modules/pact ./modules/cabana -run 'TestTokenScope\|TestScopeGroup' && scripts/check-admin-openapi.sh --check` | ✅ (extended in Plan 04) | ⬜ pending |
| SC-2 | 01 | 1 | D-18 | T-36-02 | `cabana.TokenScopeCovers` + `pier.Mount` emits structured `Warn` per plugin for uncovered backend write MCP tools (empty `Permissions` warned, `GET`/`HEAD` & `user` guard skipped, boot never fails) | unit | `go test -short ./modules/cabana ./modules/pier -run 'TestTokenScopeCovers\|TestUncoveredBackendWriteToolsWarning'` | ❌ W0 (Plan 04) | ⬜ pending |
| SC-3 | 02 | 2 | D-02, D-03, D-04, D-06, D-07, D-09, D-10, D-11, D-12, D-17 | T-36-04, T-36-05, T-36-06 | `ConnectView.vue` defaults to `Read-only (admin:read)`, hides ungrantable scopes, omits `admin:read` in Custom by default (eliminates silent PII read leak), locks `:read` rows `via admin:read` when opt-in toggled, pins `.connect-light-surface`, mobile `100dvh` sheet | component + smoke | `npm --prefix admin run typecheck && npm --prefix admin run test -- tests/views/ConnectView.test.ts tests/smoke/connect.smoke.test.ts` | ✅ (extended in Plan 04) | ⬜ pending |
| SC-4 | 02 | 2 | D-02, D-08, D-11, D-12, D-13 | T-36-04, T-36-06 | `ApiTokenCreateDialog.vue` defaults to `Read-only (admin:read)` (fallback `Full (*)`), swaps in-dialog to `ScopePicker` at fixed `max-w-[560px]` (no nested modal), Escape discards draft preserving `name`/`expires`, dark-mode semantic tokens | component | `npm --prefix admin run test -- tests/account/ApiTokenCreateDialog.test.ts tests/account/ApiTokensPanel.test.ts` | ✅ (extended in Plan 04) | ⬜ pending |
| SC-5 | 01/02/04 | 1-4 | SC-5 | T-36-01, T-36-10 | OpenAPI conformance, embedded `modules/boardwalk/dist`, en/pl phrasebooks, module READMEs & `docs/` pass all gates | gate | `scripts/check-admin-openapi.sh --check && scripts/check-admin-dist.sh && go test ./cmd/summer -run 'TestCommandsDocumented\|TestDocsTree' && go run ./cmd/summer docs:build --check` | ✅ | ⬜ pending |
| D-19 | 03 | 3 | D-19 | T-36-07, T-36-08 | `sm-sitemap-plugin` (`sitemap`, `sitemap:read`) & `sm-seo-plugin` (`seo`, `seo:read`) declare explicit `HasTokenScopes` matching existing permissions and pass `pier.Mount` zero-warning check | unit | `(cd ../sm-sitemap-plugin && go vet ./... && go test ./...) && (cd ../sm-seo-plugin && go vet ./... && go test ./...)` | ❌ W0 (Plan 03) | ⬜ pending |
| D-20 | 04 | 4 | D-20 | T-36-09 | Local `sm-grzybyfunkcjonalne-app` smoke proof shows zero boot warnings and advertises/grants Journal + SEO + Sitemap scopes | integration | `(cd ../sm-grzybyfunkcjonalne-app && go vet -tags summercms_mcp,nodynamic ./... && go test -short ./... && scripts/smoke-mcp-oauth.sh)` | ✅ | ⬜ pending |
*Status: ⬜ pending · ✅ green · ❌ red · ⚠️ flaky*
---
## Wave 0 Requirements
Per `CLAUDE.md` project rule 2 ("Unit tests are the last plan of every phase"), earlier implementation plans include smoke verification and compile/typecheck/gate runs, while comprehensive unit/component coverage lands in the final test plan (and sibling plugin unit tests land alongside the plugin scope additions):
- [ ] `modules/pier/uncovered_scopes_warning_test.go` — D-18 boot-warning coverage using `captureLogs` (`modules/pier/reaper_test.go:35`)
- [ ] `admin/tests/app/scopeCatalog.test.ts` — pure grouping, collision-safety, collation, query matching, smart expand, chip builder, submitted-scope serializer, initial state resolver
- [ ] `admin/tests/scopes/ScopeAccessControl.test.ts` — 3-tier `RadioGroupRoot`, elevated-first chip cap=6 + `+N more`, empty/disabled/invalid states
- [ ] `admin/tests/scopes/ScopePicker.test.ts` — search, filter pills, `admin:read` toggle + `via admin:read` lock, disabled `Read`, selective `Clear`, smart expand, draft/apply/discard
- [ ] `../sm-sitemap-plugin/token_scopes_test.go` & `../sm-seo-plugin/token_scopes_test.go` — `HasTokenScopes` compilation, `pier.Mount` zero-warning check, read/write token enforcement
---
## Manual-Only Verifications
| Behavior | Requirement | Why Manual | Test Instructions |
|----------|-------------|------------|-------------------|
| Visual & responsive polish on `/connect` and `/account` in light + dark mode and `< 640px` mobile sheet | D-10, D-12, D-13 | Visual layout/overflow and real browser focus/scroll behavior across light/dark theme toggle cannot be fully guaranteed by `happy-dom` | Boot `sm-grzybyfunkcjonalne-app` locally, toggle admin light/dark mode, test `/account` API token creation (in-dialog swap, Escape, dark mode) and `/connect` OAuth consent flow (desktop modal + `< 640px` DevTools mobile viewport full-screen sheet, light card in dark mode) |
| Release tag & changelog approval | D-20, `CLAUDE.md` | Pushing/tagging release versions requires explicit user go-ahead | Stop at release checkpoint before cutting patch tags on `summercms.go`, `sm-seo-plugin`, and `sm-sitemap-plugin` |
---
## Validation Sign-Off
- [ ] All tasks have `<automated>` verify or Wave 0 dependencies
- [ ] Sampling continuity: no 3 consecutive tasks without automated verify
- [ ] Wave 0 covers all MISSING references
- [ ] No watch-mode flags
- [ ] Feedback latency < 30s (quick loop)
- [ ] `nyquist_compliant: true` set in frontmatter
**Approval:** pending

View File

@@ -242,12 +242,22 @@
"number": "34", "number": "34",
"name": "Plugin marketplace", "name": "Plugin marketplace",
"status": "in_progress" "status": "in_progress"
},
{
"number": "35",
"name": "Mail templates and layouts editor",
"status": "complete"
},
{
"number": "36",
"name": "Granular MCP OAuth & API token scope picker",
"status": "pending"
} }
], ],
"next": { "next": {
"command": "/msd:progress --next", "command": "/gsd:progress --next",
"label": "Advance to the next step (plan phase 19.3)", "label": "Advance to the next step",
"reason": "Phase 19.3 of 53 — needs a plan" "reason": "Phase 36 of 54 · executing"
}, },
"updated_at": "2026-11-21T18:14:38.197Z" "updated_at": "2026-11-24T17:54:17.179Z"
} }